IHttpHandler的学习(0-2)

这个IHttpHandler,要想到asp.net生命周期 ,想到哪个从你发起请求开始,这个请求通过HttpModule------》IHttpHandler的;

执行HttpModule的一系列事件后然后执行HttpHandler,然后又执行HttpModule的一些事件。

从图中可以看出,你发送的http请求的最后是在HttpHandler中处理的;
HttpModule是一个HTTP请求的“必经之路”
所以在请求还没有到达HttpHandler的时候,可以对这个请求附加一些信息。
或者针对截获的这个HTTP请求信息作一些额外的工作,或者在某些情况下干脆终止满足一些条件的HTTP请求,从而可以起到一个Filter过滤器的作用。
(过滤器???哈?,怎么在我脑海里冒出来:此路是我开,要想从此过,留下买路财)

一个HTTP请求在HttpModule容器的传递过程中,会在某一时刻(ResolveRequestCache事件)将这个HTTP请求传递给HttpHandler容器。在这个事件之后,HttpModule容器会建立一个HttpHandler的入口实例,但是此时并没有将HTTP请求控制权交出,而是继续触发AcquireRequestState事件以及PreRequestHandlerExcute事件。在PreRequestHandlerExcute事件之后,HttpModule窗口就会将控制权暂时交给HttpHandler容器,以便进行真正的HTTP请求处理工作。

而在HttpHandler容器内部会执行ProcessRequest方法来处理HTTP请求。在容器HttpHandler处理完毕整个HTTP请求之后,会将控制权交还给HttpModule,HttpModule则会继续对处理完毕的HTTP请求信息流进行层层的转交动作,直到返回到客户端为止。

例子看原文吧

MyHttpModule代码

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 
 6 namespace MyHttpModule
 7 {
 8     /// <summary>
 9     /// 自定义HttpModule;看到这个鬼,就要想到继承IHttpModule接口和在config中配置信息
///注意标红的这三个方法:请求信息先进入到Init初始化的方法里,然后进入 10 /// </summary> 11 public class MyHttpModule : IHttpModule 12 { 13 public void Dispose() 14 { 15 throw new NotImplementedException(); 16 } 17 18 public void Init(HttpApplication context) 19 { 20 context.BeginRequest += context_BeginRequest; 21 context.EndRequest += context_EndRequest; 22 } 23 24 void context_EndRequest(object sender, EventArgs e) 25 { 26 HttpApplication app = sender as HttpApplication; 27 if (app != null) 28 { 29 HttpContext context = app.Context; 30 HttpResponse response = app.Response; 31 response.Write("自定义HttpModule中的EndRequest"); 32 33 } 34 } 35 36 void context_BeginRequest(object sender, EventArgs e) 37 { 38 HttpApplication app = sender as HttpApplication; 39 if (app != null) 40 { 41 HttpContext context = app.Context; 42 HttpResponse response = app.Response; 43 response.Write("自定义HttpModule中的BeginRequest"); 44 45 } 46 } 47 } 48 }
复制代码

在web.config注册自定义的HttpModule

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!--
 3   For more information on how to configure your ASP.NET application, please visit
 4   http://go.microsoft.com/fwlink/?LinkId=169433
 5   -->
 6 <configuration>
 7   <system.web>
 8     <compilation debug="true" targetFramework="4.5" />
 9     <httpRuntime targetFramework="4.5" />
10    
11   </system.web>
12   <system.webServer>
13     <modules>
14       <add name="MyHttpModule" type="MyHttpModule.MyHttpModule,MyHttpModule"/>
15     </modules>
16   </system.webServer>
17 </configuration>
复制代码

浏览页面Default.aspx

猜你喜欢

转载自www.cnblogs.com/ZkbFighting/p/9022362.html