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 MyHttpModule7 {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 visit4 http://go.microsoft.com/fwlink/?LinkId=1694335 -->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
?
轉載于:https://www.cnblogs.com/ZkbFighting/p/9022362.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的IHttpHandler的学习(0-2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CBC字节翻转攻击
- 下一篇: jquery 属性操作