Uncategorized

ASP.NET による HTTP Request のキャプチャー

こんにちは。

ASP.NET を使って、HTTP の Request をキャプチャー (Capture) するコードです。
例えば、Microsoft Azure にホストして Remote Debug することで、どんな要求が渡されているか確認できます。(まあ、ログを取れば良いのですが、たまに必要になるんです。この投稿は公開せず、自分へのメモのために掲載しておきます。)

まず、クラスを追加して、以下の IHttpModule クラスを実装します。

. . .using System.Text;. . .public class MyTrackModule : IHttpModule{  public void Init(HttpApplication context)  {    context.BeginRequest += context_BeginRequest;    context.EndRequest += context_EndRequest;  }  void context_BeginRequest(object sender, EventArgs e)  {    HttpApplication application = (HttpApplication)sender;    HttpContext context = application.Context;    string method = context.Request.HttpMethod;    string url = context.Request.Url.AbsoluteUri;    string querystring = context.Request.QueryString.ToString();    StringBuilder headerBuilder = new StringBuilder();     foreach (string key in application.Request.Headers.Keys)    {      headerBuilder.Append(key);      headerBuilder.Append(": ");      headerBuilder.Append(application.Request.Headers[key]);      headerBuilder.Append("n");    }    string headers = headerBuilder.ToString();    byte[] bytes = application.Request.BinaryRead(application.Request.ContentLength);    string body = Encoding.ASCII.GetString(bytes);    application.Request.InputStream.Position = 0;    // print (log) : method, url, querystring, headers, body    . . .  }  void context_EndRequest(object sender, EventArgs e)  {    // No code  }  public void Dispose()  {    // No code  }}. . .

あとは、Web.config に下記の通り設定して、この Custom Module を使用するように設定して終了です。

ASP.NET MVC などの場合には、Views フォルダーにも Web.config があるので注意してください。(Views の Web.config も書き換えておきます。)

<?xml version="1.0"?><configuration>  . . .  <system.webServer>    <modules runAllManagedModulesForAllRequests="true">      <add name="MyTrackModule"        type="WebApplication1.MyTrackModule" />    </modules>    . . .  </system.webServer></configuration>

Categories: Uncategorized

Tagged as: ,

Leave a Reply