Asp.net 中HttpHandler,HttpModule,IHttpHandlerFactory的原理与应用(一)
引用地址:http://hi.baidu.com/chenying99/blog/item/ab51e4ea708bd6d5d439c955.html 最近对页面的生命周期比较感兴趣,看了一些牛人们写的文章,感觉似懂非懂(仍需要继续努力^_^). //Class: HttpModuleTest.cs //--------------------------------------------- using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// HttpModuleTest 的摘要描述 /// </summary> public class HttpModuleTest:IHttpModule { //Init方法用来注册HttpApplication 事件。 public void Init(HttpApplication application) { application.BeginRequest += (new EventHandler(this.Application_BeginRequest)); application.EndRequest += (new EventHandler(this.Application_EndRequest)); } //在页面处理前执行这个事件方法 private void Application_BeginRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("<h1><font color=red> HelloWorldModule: Beginning of Request</font></h1><hr>"); context.Response.Write("<a href='http://www.baidu.com'><h2><font color=blue>click here you will see some ads</font></h2></a>"); } //在页面处理前执行这个事件方法 private void Application_EndRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("<hr><h1><font color=red>HelloWorldModule: End of Request</font></h1>"); } //资源释放 public void Dispose() { } } //-----------------------------------------------
<httpModules > <add name="test" type ="HttpModuleTest,HttpModuleTest"/> </httpModules>
public class IpFilterModule:IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { //在事件处理过程中,我们可以获得当前请求的上下文,根据请求的上下文,我们可以对 //请求执行任何操作 HttpApplication app = sender as HttpApplication; //获得当前应用程序 if (app != null) { //app.Context 获得当前上下文信息 string hostname = app.Context.Request.UserHostName; if (hostname!="cc") { app.Context.Response.StatusCode = 404; app.Context.Response.End(); } } } public void Dispose() { } }
|