HttpModule做用是 IIS将接收到的请求分发给相应的ISAPI处理前,先截获该请求。web
经过这个咱们能够完成不少额外功能。app
自定义IHttpModule的例子:asp.net
经过自定义HttpModule,页面加载前劫持请求,向页面输入文字“MyModule”。网站
1.在asp.net站点下添加App_Code文件夹,而后添加MyModule类。spa
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace WebApplication4 { public class MyModule:IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { //context.BeginRequest是开始处理HTTP管线请求时发生的事件 context.BeginRequest += new EventHandler(context_BeginRequest); //context.Error是当处理过程当中发生异常时产生的事件 //context.Error += new EventHandler(context_Error); } void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; HttpResponse response = context.Response; response.Write("MyModule"); } } }
2.配置WebConfig。注册自定义IHttpModule.net
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <system.webServer> <modules> <add name="MyModule" type="WebApplication4.MyModule,WebApplication4"/> </modules> </system.webServer> </configuration>
type值为DLL命名空间
3.运行网站,查看效果
4.可能遇到的错误:
请将MyModule.cs 文件生成操做设置为:编译。