HTTPFilter 的例子

using System;
using System.Web;
using System.Diagnostics;


namespace HDI
{
  public class HTTPFilter : IHttpModule
  {

    System.IO.StreamWriter fileWriter;
    HttpApplication applicationContext;
    EventHandler beginRequestEventHandler;
    String fileName;

    public void Init(HttpApplication context)
    {
      //Store file name for later use.
      fileName = context.Context.Request.PhysicalApplicationPath + "HTTPFilter.txt";

      //Open file and write information.
      fileWriter = new System.IO.StreamWriter(fileName, true);
      fileWriter.WriteLine(System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss:ffffff"));
      fileWriter.WriteLine("Init");
      fileWriter.Flush();
      fileWriter.Close();

      context.Error += (new EventHandler(this.Application_err));

             


      //Store for access in other events.
      applicationContext = context;
      beginRequestEventHandler = new System.EventHandler(this.OnBeginRequest);
      applicationContext.BeginRequest += beginRequestEventHandler;
    }

    public void Dispose()
    {

      //Open file and write information.
      fileWriter = new System.IO.StreamWriter(fileName, true);
      fileWriter.WriteLine(System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss:ffffff"));
      fileWriter.WriteLine("Dispose");
      fileWriter.Flush();
      fileWriter.Close();

      //Clean-up.
      applicationContext.BeginRequest -= beginRequestEventHandler;
      beginRequestEventHandler = null;
    }

      protected void OnBeginRequest(object sender, EventArgs e)
      {
          //Open file and write information.
          fileWriter = new System.IO.StreamWriter(fileName, true);
          fileWriter.WriteLine(System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss:ffffff"));
          fileWriter.WriteLine("OnBeginRequest");
          fileWriter.WriteLine(applicationContext.Context.Request.UserAgent);
          fileWriter.WriteLine(applicationContext.Context.Request.UserHostAddress);
          fileWriter.WriteLine(applicationContext.Context.Request.Url.ToString());
          fileWriter.Flush();
          fileWriter.Close();
      }

      protected void Application_err(object sender, EventArgs e)
      {
          //Open file and write information.
          fileWriter = new System.IO.StreamWriter(fileName, true);
          fileWriter.WriteLine(System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss:ffffff"));
          fileWriter.WriteLine( applicationContext.Context.Error.Message+applicationContext.Context.AllErrors.ToString());

//Context.Server.GetLastError()
          fileWriter.Flush();
          fileWriter.Close();
      }

  }
}

你可能感兴趣的:(filter)