ASP.NET MVC理解HttpModule的作用并自定义HttpModule

预备知识


首先先来一张ASP.NET 请求管道的图,这张图里包含了HttpModule在请求管道的作用,有助于下面对HttpModule的理解
ASP.NET MVC理解HttpModule的作用并自定义HttpModule_第1张图片
如果有什么错误,欢迎留言,或者说对这张图不能理解的话可以网上查 ASP.NET请求管道 ,有很多优秀的文章

HttpModule的作用


结合根据上面的流程红框,我们可以看出HttpModule的作用是“在HttpContext到达我们真正处理请求,也就是调用MvcHandler的ProcessRequest事件之前,我们可以通过自定义的HttpModule对HttpContext进行预处理,通过这种方式来实现我们的需求。

自定义HttpModule

在我们 ASP.NET MVC项目里面创建一个类,继承于IHttpModule并实现Init方法,这里我自定义了两个httpModule

   public class MySecondModule : IHttpModule
    {
      public void Dispose()
      {   //对此方法先不实现
             throw new NotImplementedException();
       }
      public void Init(HttpApplication context)
       { 
          //订阅HttpApplication中BeginRequst事件
          context.BeginRequest += Context_BeginRequest;
          //订阅HttpApplication中EndRequest事件
          context.EndRequest += Context_EndRequest;
       }
        private void Context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpResponse httpResponse = httpApplication.Context.Response;
            //对HttpContext的Response写入信息
            httpResponse.Write("

MySecondModule执行了Context_EndRequest

"); } private void Context_BeginRequest(object sender, EventArgs e) { HttpApplication httpApplication = (HttpApplication)sender; HttpResponse httpResponse = httpApplication.Context.Response; //对HttpContext的Response写入信息 httpResponse.Write("

MySecondModule执行了Context_BeginReqeust

"); } }
   public class MyModule : IHttpModule
    {
        public void Dispose()
        {  //对此方法先不实现
            throw new NotImplementedException();
        }
        
        public void Init(HttpApplication context)
        {
            //订阅HttpApplication中BeginRequst事件
            context.BeginRequest += Context_BeginRequest;
            //订阅HttpApplication中EndRequest事件
            context.EndRequest += Context_EndRequest;  
        }
        
        private void Context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpResponse response = application.Context.Response;
            //对HttpContext的Response写入信息
            response.Write("

MyModule执行了Context_EndRequest

"); } private void Context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpResponse response = application.Context.Response; //对HttpContext的Response写入信息 response.Write("

MyModule执行了Context_BeginRequest

"); } }

实现过后,在Web.config进行注册,在Web.config,要区分IIS7集成模式和II7的经典模式(包括IIS6)

     
    
      
      
      
    
    
    
    
              
      
      
      
    

add里面type里面填的格式是     程序集+类名 例如我的MyModule位置在 Asp.net_Form认证.Module.MySecondModule 添加HttpModule的顺序决定了那个HttpModule先调用

注册完之后运行我们的程序
ASP.NET MVC理解HttpModule的作用并自定义HttpModule_第2张图片

你可能感兴趣的:(ASP.NET MVC理解HttpModule的作用并自定义HttpModule)