代码改变世界

自定义IHttpModule的小实例

2011-07-03 11:35  Simon.Jiang  阅读(970)  评论(2编辑  收藏  举报

在网站开发过程中,往往需要对每个请求添加自定义的一些逻辑,比如ip验证等,所以自定义IHttpModule的实现就可以帮上很大的忙。但是,添加自定义的IHttpModule模块不适合处理很复杂的逻辑,因为每一个请求都会经过该模块的处理,从而导致请求处理性能低下。

 

1、新建自己的处理逻辑,并实现IHttpModule接口。

View Code
1 using System;
2  using System.Data;
3  using System.Configuration;
4  using System.Linq;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.HtmlControls;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.WebControls.WebParts;
11 using System.Xml.Linq;
12
13 namespace Taotao.Test.HttpModule
14 {
15 public class HelloWorldModule : IHttpModule
16 {
17 public void Dispose()
18 {
19
20 }
21
22 public void Init(HttpApplication context)
23 {
24 context.BeginRequest += new EventHandler(context_BeginRequest);
25 context.EndRequest += new EventHandler(context_EndRequest);
26 }
27
28 void context_EndRequest(object sender, EventArgs e)
29 {
30 HttpApplication application = (HttpApplication)sender;
31 HttpContext context = application.Context;
32 string filePath = context.Request.Path;
33 string fileExtension = VirtualPathUtility.GetExtension(filePath);
34 if (fileExtension.Equals(".aspx"))
35 {
36 context.Response.Write("<h1 style=\"color:red;\">HelloWorldModule:Ending Of The Request.</h1><hr>");
37 }
38 }
39
40 void context_BeginRequest(object sender, EventArgs e)
41 {
42 HttpApplication application = (HttpApplication)sender;
43 HttpContext context = application.Context;
44 string filePath = context.Request.Path;
45 string fileExtension = VirtualPathUtility.GetExtension(filePath);
46 if (fileExtension.Equals(".aspx"))
47 {
48 context.Response.Write("<h1 style=\"color:red;\">HelloWorldModule:Beginning Of The Request.</h1><hr>");
49 }
50 }
51 }
52 }

2、在web.config中进行配置还是很重要的。在<System.Web><HttpModules>添加自己的HttpModule。

View Code
1 <add name="HelloWorldModule" type="Taotao.Test.HttpModule.HelloWorldModule,Taotao.Test.HttpModule"/>

添加HttpModule配置有两个必须的属性,那就是name和type,name属性可以随意,但是不能跟其他HttpModule有重名;type属性有两部分组成,他们以英文逗号隔开,第一部分是自定义HttpModule(HelloWorldModule)类的完整路径,第二不部分是自定义HttpModule类所在的命名空间的完整路径。

上面两个步骤完成后,调试一下,可以看到在每个你请求的aspx页面上都会出现自定义HttpModule输出的内容。