要实现HttpModule,必须实现接口IHttpModule。下面是IHttpModule接口分析:

using System;
namespace System.Web
{
    public interface IHttpModule
    {
        //   销毁不再被HttpModule使用的资源
        void Dispose();
        // 初始化一个Module,为捕获HttpRequest做准备
        void Init(HttpApplication context);
    }

下面是自己的HttpModule:

using System;
using System.Web;
namespace ClassLibrary1
{
    public class MyHttpModule : IHttpModule
    {
        public void Dispose() { }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Application_BeginRequest);
            context.EndRequest += new EventHandler(Application_EndRequest);
        }
        public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;
            HttpResponse response = context.Response;
            response.Write("这是来自自定义HttpModule中有BeginRequest");
        }
        public void Application_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            HttpContext context = application.Context;
            HttpResponse response = context.Response;
            response.Write("这是来自自定义HttpModule中有EndRequest");
        }
    }
}

web.config

<httpModules>
      <add name="myHttpModule" type="ClassLibrary1.MyHttpModule,ClassLibrary1"/>
    </httpModules>

default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("<br/><br/>来自Default.aspx页面<br/>");
    }
}
HttpModule 最后修改于 2011-09-26 21:48:17
上一篇