天天看點

了解并自定義HttpModule

前言                                  

目錄                                  

  asp.net的事件分為三級:應用程式級、頁面級和控件級。而httpmodule是通過在管道模型中對asp.net的應用程式級事件進行

訂閱,當應用程式級事件觸發時調用httpmodule中對應的處理方法。也就是說httpmodule是訂閱asp.net應用程式級事件的入口,依附

于httpapplication對象生命周期的各個事件。

  asp.net内部很多功能都以httpmodule形式來實行,如windows、forms和passport認證、session機制等。下面是部分的内部httpmodule及其作用。

名稱

類型

功能

outputcache

system.web.caching.outputcachemodule

頁面級輸出緩存

session

system.web.sessionstate.sessionstatemodule

session狀态管理

windowsauthentication

system.web.security.windowsauthenticationmodule

用內建windows身份驗證進行用戶端驗證

formsauthentication

system.web.security.formsauthenticationmodule

用基于cookie的窗體身份驗證進行用戶端身份驗證

passportauthentication

system.web.security.passportauthenticationmodule

用ms護照進行客戶身份驗證

rolemanager

system.web.security.rolemanagermodule

管理目前使用者角色

urlauthorization

system.web.security.urlauthorizationmodule

判斷使用者是否被授權通路某一url

fileauthorization

system.web.security.fileauthorizationmodule

判斷使用者是否被授權通路某一資源

anonymousidentification

system.web.security.anonymousidentificationmodule

管理asp.net應用程式中的匿名通路

profile

system.web.profile.profilemodule

管理使用者檔案檔案的創立 及相關事件

errorhandlermodule

system.web.mobile.errorhandlermodule

捕捉異常,格式化錯誤提示字元,傳遞給用戶端程式

  自定義httpmodule跟自定義httphandler相似,都要在web.config檔案中進行配置。形式如下:

1.type:跟httphandler中的一樣,有兩部分組成,第一部分是完整的類名(含命名空間名),第二部分是所在程式集名(不含.dll)。

2.name:httpmodule的名稱,可以跟類名無關。通過httpapplication對象的modules屬性擷取

httpmodulecollection,然後通過name擷取對應的httpmodule對象;在global.asax中通過方法名

modulename_eventname訂閱httpmodule中的事件,這裡為mm_具體的事件名,詳細請見下面執行個體。

3.因為對于每個進入工作程序的請求都會經過各已配置的httpmodule的處理(因為httpmodule是訂閱應用程式級事件的),是以配置檔案中沒有path和verb屬性(不管是*.aspx還是*.ashx,請求方式為get還是post都會進行處理)。

注意:httpmodule的配置是無需像httphandler那樣在iis上進行配置的。

  每個httpmodule都繼承system.web.ihttpmodule接口,并實作接口的init(httpapplication context)和dispose()方法。如下:

init():這個方法接受一個httpapplication對象,httpapplication代表了當

前的應用程式,我們需要在這個方法内訂閱

httpapplication對象暴露給用戶端的事件。可見,這個方法僅僅是用來對事件進行訂閱,而實際的事件處理程式,需要我們另外寫方法。

dispose():在垃圾回收前釋放資源。

整個過程很好了解:

當站點第一個資源被通路的時候,asp.net會建立httpapplication類的執行個體,它代表着站點應用程式,同時會建立所有在web.config中注冊過的module執行個體。

在建立module執行個體的時候會調用module的init()方法。

在init()方法内,對想要作出響應的httpapplication暴露出的事件進行注冊。(僅僅進行方法的簡單注冊,實際的方法需要另寫)。

httpapplication在其應用程式周期中觸發各類事件。

觸發事件的時候調用module在其init()方法中注冊過的方法。

在asp.net中,glabal不僅可以注冊應用程式和session事件,還可以注冊http module暴露出的事件;不僅可以注冊系統module的事件,也可以注冊我們自己義的module暴露出的事件。在具體介紹之前,這裡需要首先注意兩點:

在每處理一個http請求時,應用程式事件都會觸發一遍,但是application_start和 application_end 例外,它僅在第一個資源檔案被通路時被觸發。

http module無法注冊和響應session事件,對于session_start 和 session_end,隻能通過glabal.asax來處理。

繼續上面的例子:

mymodule.cs檔案

global.asax檔案

上面的mymodule_exposedevent方法就會自動訂閱了mymodule中的exposedevent事件。具體實作機制有待研究!

繼續閱讀