预备知识
首先先来一张ASP.NET 请求管道的图,这张图里包含了HttpModule在请求管道的作用,有助于下面对HttpModule的理解
如果有什么错误,欢迎留言,或者说对这张图不能理解的话可以网上查 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("<p>MySecondModule执行了Context_EndRequest</p>");
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication httpApplication = (HttpApplication)sender;
HttpResponse httpResponse = httpApplication.Context.Response;
//对HttpContext的Response写入信息
httpResponse.Write("<p>MySecondModule执行了Context_BeginReqeust</p>");
}
}
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("<p>MyModule执行了Context_EndRequest</p>");
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpResponse response = application.Context.Response;
//对HttpContext的Response写入信息
response.Write("<p>MyModule执行了Context_BeginRequest</p>");
}
}
实现过后,在Web.config进行注册,在Web.config,要区分IIS7集成模式和II7的经典模式(包括IIS6)
<!--IIS6或IIS7的经典模式-->
<httpModules>
<add name="MySecondModule" type="Asp.net_Form认证.Module.MySecondModule"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
<add name="MyModule" type="Asp.net_Form认证.Module.MyModule"></add>
</httpModules>
<!--IIS7集成模式-->
<modules>
<add name="MyModule" type="Asp.net_Form认证.Module.MyModule"></add>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
<add name="MySecondModule" type="Asp.net_Form认证.Module.MySecondModule"/>
</modules>
add里面type里面填的格式是 程序集+类名 例如我的MyModule位置在 Asp.net_Form认证.Module.MySecondModule 添加HttpModule的顺序决定了那个HttpModule先调用
注册完之后运行我们的程序