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

HTTPヘッダを取得するコードを紹介します。

概要

ASP.NETアプリケーションで、HTTPヘッダのパラメータを取得したいことがあります。HTTPヘッダはHTTPコンテントのように、context.Request.InputStreamプロパティからストリームを取得することはできません。ヘッダを取り出す場合は、HttpRequestクラスのHeadersプロパティを用います。HeadersプロパティはServerVariablesプロパティとは異なり、AUTH_USERやAPPL_PHYSICAL_PATHなどのサーバ環境変数は含んでいません。

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

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

HTTPヘッダの内容をページのテキストボックスに表示するプログラムです。

UI

下図のWebフォームのページを作成します。ページにTextModeプロパティをMultiLineに設定した複数行のテキストボックスを配置します。


HttpHeaderDisplay.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HttpHeaderDisplay.aspx.cs" Inherits="HttpHeaderDemo.HttpHeaderDisplay" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server" Height="353px" TextMode="MultiLine" Width="650px"></asp:TextBox>
        </div>
    </form>
</body>
</html>

コード

Webフォームのコードに下記のコードを記述します。
HttpHeaderDisplay.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HttpHeaderDemo
{
  public partial class HttpHeaderDisplay : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      for (int i = 0; i < Request.Headers.Keys.Count; i++) {
        string s = Request.Headers.Keys[i];
        string[] v = Request.Headers.GetValues(s);
        string values="";
        for (int j = 0; j < v.Length; j++) {
          values += v[j] + " ";
        }

        TextBox1.Text += s + ":" + values +"\r\n";
      }
    }
  }
}

解説

ASP.NET Webフォームでは、リクエストヘッダの情報は Request.Headers オブジェクト内に格納されています。
ヘッダのキーの数をRequest.Headers.Keys.Countで取得し、キーの名称は Request.Headers.Keys[i] で取得できます。
キーに対応する値は Request.Headers.GetValues([キー名]) で取得できます。キー名と値を整形してテキストボックスに表示しています。

実行結果

プロジェクトを実行し、WebブラウザでWebフォームを表示します。リクエストヘッダの内容が、テキストボックスに表示されます。

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

HTTPヘッダの内容をすべてテキストファイルに保存するプログラムです。
プロジェクトの新規作成で空のASP.NET Webアプリケーションを作成し、ジェネリックハンドラーを追加します。ジェネリックハンドラーのProcessRequestメソッドに以下のコードを記述します。

コード

HttpHeaderDumpHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace HttpHeaderDemo
{
  /// <summary>
  /// HttpHeaderDumpHandler の概要の説明です
  /// </summary>
  public class HttpHeaderDumpHandler : IHttpHandler
  {

    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "text/plain";
      context.Response.Write("Accept");

      string Header = "";
      for (int i = 0; i < context.Request.Headers.Keys.Count; i++) {
        string s = context.Request.Headers.Keys[i];
        System.Diagnostics.Debug.WriteLine(s);
        Header += s + " : ";
        string[] v = context.Request.Headers.GetValues(s);
        for (int j = 0; j < v.Length; j++) {
          Header += v[j] + " ";
        }
        Header += "\r\n";
      }
      System.Diagnostics.Debug.WriteLine(Header);

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

    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}

解説

基本的な動作はページに表示する場合と同様です。リクエストヘッダの情報はcontext.Request.Headersオブジェクトに格納されています。 ヘッダ内のキーの個数はcontext.Request.Headers.Keys.Count で取得でき、キーの名称はcontext.Request.Headers.Keys[i]で取得できます。
キーに対応する値はcontext.Request.Headers.GetValues([キー名])で取得します。取得したキーの名称とキーの値を整形してテキストファイルに出力しています。

実行結果

ジェネリックハンドラのURLアクセスします。Accept のメッセージが表示されます。


ジェネリックハンドラにアクセス後、c:\data フォルダ内に dump.txt ファイルが作成されます。

出力内容 (c:\data\dump.txt)

ジェネリックハンドラにアクセスすると、c:\data\dump.txt に以下の内容のファイルが作成されます。

c:\data\dump.txt 出力例1
Connection : close 
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 
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.171106476.1599829419; _ga_F81X5MMRN8=GS1.1.1599829418.25.0.1599829422.56 
Host : localhost:44305 
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 
c:\data\dump.txt 出力例2
Connection : Keep-Alive
Accept : image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Encoding : gzip, deflate
Accept-Language : ja-JP
Cookie : MGUID=MGUID-20090824-153559-47029820; FSUID=FSUID-20091015-135853-4536; __utmmobile=0x4F39C50760C17755
Host : localhost:50327
Referer : http://localhost:50327/
User-Agent : Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-08-25
作成日: 2010-10-25
iPentec all rights reserverd.