要实现HttpModule,必须实现接口IHttpModule。
using System;
namespace System.Web
{
public interface IHttpModule
{
// 销毁不再被HttpModule使用的资源
void Dispose();
// 初始化一个Module,为捕获HttpRequest做准备
void Init(HttpApplication context);
}
}
下面是自己的HttpModule
/// <summary>
/// 需要在网站的 Web.config 文件中配置此模块,向 IIS 注册它,然后才能使用它。
/// </summary>
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute);
context.BeginRequest += new EventHandler(Application_BeginRequest);
context.EndRequest += new EventHandler(Application_EndRequest);
}
public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
string url = application.Request.RawUrl;
if (url.Contains("HttpModule_HtmlTest"))
{
application.Response.Redirect("~/HttpModule_Index.html");
application.Response.End();
}
else if (url.Contains("HttpModule_JsonTest"))
{
dynamic obj = new System.Dynamic.ExpandoObject();
obj = new
{
res = 0,
msg = "请求被拦截!",
};
string jsonRes = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
application.Response.Write(jsonRes);
application.Response.ContentType = "text/html;charset=UTF-8";
application.Response.End();
}
}
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");
}
public void Dispose()
{
}
}
web.config
1 <!--自定义过滤器IIS6(对IIS7的经典模式起作用) --> 2 <system.web> 3 <httpModules> 4 <add name="myHttpModule" type="namespace.MyHttpModule, namespace" /> 5 </httpModules> 6 </system.web> 7 <system.webServer> 8 <!-- 在IIS7的集成模式下,加上了preCondition="managedHandler"这个配置项后,就不会去处理静态文件(.html .css .js .jpeg等)的请求了,只会处理托管文件(aspx, ascx 及 MVC等)的请求 9 <add name="webServerHttpModule" type="namespace.MyHttpModule, namespace" preCondition="managedHandler" /> 10 --> 11 <modules> 12 <add name="webServerHttpModule" type="namespace.MyHttpModule, namespace" /> 13 </modules> 14 </system.webServer>