HTTPヘッダを取得する (HTTPヘッダのダンプ) - ASP.NET Core

ASP.NET Core Webアプリケーションで、HTTPヘッダを取得するコードを紹介します。

概要

ASP.NET Core アプリケーションで、HTTPヘッダのパラメータを取得したいことがあります。
ASP.NET Core アプリケーションでは、context.Request.Headers オブジェクトにアクセスすることでHTTPリクエストヘッダを取得できます。

補足
ASP.NET (.NET Frameworkd版)の場合の対応方法、プログラムはこちらの記事を参照してください。

プログラム例 (HTTPヘッダのページへの表示)

HTTPヘッダの内容をすべてページに出力するプログラムです。
ASP.NET Core アプリケーションを作成し、RazorPageを追加します。

コード : RazorPages

下記のコードを記述します。
Pages/ShowRequestHeader.cshtml
@page
@model RequestHeaderDemo.Pages.ShowRequestHeaderModel
@{
}
<!DOCTYPE html>
<html>
<head>
  <title>Request Header Demo</title>
</head>
<body>
  <div>Request Header Demo</div>
  <hr />
  <div style="font-size:.8rem; border:1px solid #A0A0A0;">
    @Html.Raw(@Model.RequstHeaderStr.Replace("\r\n", "<br/>"))
  </div>
</body>
</html>
Pages/ShowRequestHeader.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Primitives;

namespace RequestHeaderDemo.Pages
{
  public class ShowRequestHeaderModel : PageModel
  {
    public string RequstHeaderStr { get; set; }

    public void OnGet()
    {
      RequstHeaderStr = "";
      foreach (string key in Request.Headers.Keys) {
        StringValues values;
        Request.Headers.TryGetValue(key, out values);
        RequstHeaderStr += key + " : ";
        foreach (string value in values) {
          RequstHeaderStr += value + " ";
        }
        RequstHeaderStr += "\r\n";
      }
    }
  }
}

コード : Startup.cs

Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace RequestHeaderDemo
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapRazorPages();
      });
    }
  }
}

解説

ASP.NET Core アプリケーションの基本的な動作やRazor Pagesの動作についてはこちらの記事を参照してください。

ページモデルのクラスでは、RequstHeaderStr プロパティを宣言します。publicプロパティとして宣言するため、ページ側からモデルオブジェクトを経由してRequstHeaderStr プロパティを参照できます。
リクエストヘッダの情報は Request.Headers に格納されています。foreachループで、Request.Headers.Keys の値(キー名)をすべて取得します。 キーに対応する値は Request.Headers.TryGetValue([キー名], out [値]) で取得します。values 変数にキーに対応する値(複数の値)が返されます。
foreachループを利用して、valuesの値を一つずつ取得し、文字列に整形します。
文字列をRequstHeaderStrプロパティに代入してページから参照できるようにします。
  public class ShowRequestHeaderModel : PageModel
  {
    public string RequstHeaderStr { get; set; }

    public void OnGet()
    {
      RequstHeaderStr = "";
      foreach (string key in Request.Headers.Keys) {
        StringValues values;
        Request.Headers.TryGetValue(key, out values);
        RequstHeaderStr += key + " : ";
        foreach (string value in values) {
          RequstHeaderStr += value + " ";
        }
        RequstHeaderStr += "\r\n";
      }
    }
  }

ページ側ではモデルクラスのRequstHeaderStrプロパティの値を画面に表示します。 そのまま表示すると改行などが反映されないため、改行コードを <br/>タグに置換して画面にレンダリングしています。
    @Html.Raw(@Model.RequstHeaderStr.Replace("\r\n", "<br/>"))

実行結果

プロジェクトを実行し、Webブラウザで (アプリケーションルートURL)/ShowRequestHeader にアクセスします。下図の画面が表示されます。 ページにリクエストヘッダの内容が表示されることが確認できます。

プログラム例 (HTTPヘッダのダンプ)

HTTPヘッダの内容をすべてテキストファイルに保存するプログラムです。
プロジェクトの新規作成で空のASP.NET Core Webアプリケーションを作成し、Startup.cs ファイルを編集します。

コード

下記のコードを記述します。
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives;
using System.IO;

namespace RequestHeaderDemo
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/DumpHeader", async context =>
              {
                await context.Response.WriteAsync("Accept");

                string Header = "";
                foreach (string key in context.Request.Headers.Keys) {
                  StringValues values;
                  context.Request.Headers.TryGetValue(key, out values);
                  Header += key + " : ";
                  foreach (string value in values) {
                    Header += value + " ";
                  }
                  Header += "\r\n";
                }

                StreamWriter sw = new StreamWriter(@"c:\data\dump.txt", true, System.Text.Encoding.ASCII);
                sw.Write(Header);
                sw.Close();
              });
      });
    }
  }
}

実行結果

プロジェクトを実行します。実行後 (アプリケーションルートURL)/DumpHeader のURLにWebブラウザでアクセスします。 正しく動作すると画面に "Accept" のメッセージが表示されます。


アクセス後に、c:\data ディレクトリに dump.txt ファイルが作成されます。

出力結果

dump.txtファイルには以下の内容が書き込まれます。
dump.txt (出力例1)
Accept : text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 
Accept-Encoding : gzip, deflate, br 
Accept-Language : ja,en;q=0.9,en-GB;q=0.8,en-US;q=0.7 
Connection : close 
Cookie : _ga=GA1.1.1604535004.1591804955; FSUID=FSUID-20200615-230812-8478; __gads=ID=1182f7865b4f04a3-22973dfd2ac200b5:T=1592660487:RT=1592660487:S=ALNI_Ma72gF4KfR8U5pKwQVIybMVItLpHQ; _gid=GA1.1.1393705732.1599986176; _ga_F81X5MMRN8=GS1.1.1599986175.26.1.1599986781.60 
Host : localhost:44327 
User-Agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36 Edg/85.0.564.51 
upgrade-insecure-requests : 1 
sec-fetch-site : none 
sec-fetch-mode : navigate 
sec-fetch-user : ?1 
sec-fetch-dest : document 
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-08-18
作成日: 2020-09-13
iPentec all rights reserverd.