作者:孫亞民
HttpHandler實現(xiàn)了類似于ISAPI Extention的功能,他處理請求(Request)的信息和發(fā)送響應(yīng)(Response)。HttpHandler功能的實現(xiàn)通過實現(xiàn)IHttpHandler接口來達(dá)到。而HttpModule實現(xiàn)了類似于ISAPI Filter的功能。
HttpModule的實現(xiàn)
HttpModules實現(xiàn)了類似于ISAPI Filter的功能,在開發(fā)上,通常需要經(jīng)過以下步驟:
1.編寫一個類,實現(xiàn)IhttpModule接口
2.實現(xiàn)Init 方法,并且注冊需要的方法
3.實現(xiàn)注冊的方法
4.實現(xiàn)Dispose方法,如果需要手工為類做一些清除工作,可以添加Dispose方法的實現(xiàn),但這不是必需的,通常可以不為Dispose方法添加任何代碼。
5.在Web.config文件中,注冊您編寫的類
下面是一個HttpModules的示例,在這個示例中,只是簡單的注冊了HttpApplication 的BeginRequest 和 EndRequest事件,并且通過這些事件的實現(xiàn)方法,將相關(guān)的信息打印出來。
例1:
using System;
using System.Web;
namespace MyModule
{
public class MyModule : IHttpModule
{
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;
HttpResponse Response=Application.Context.Response;
Response.Write("<h1>Beginning of Request</h1><hr>");
}
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpResponse Response=Application.Context.Response;
Response.Write("<h1>End of Request</h1><hr>");
}
public void Dispose()
{
}
}
}
程序的開始引用了如下名稱空間:
using System;
using System.Web;
因為HttpApplication、HttpContext、HttpResponse等類在System.Web中定義,因此,System.Web名稱空間是必須引用的。
MyModule類實現(xiàn)了IhttpModule接口。在Init方法中,指明了實現(xiàn)BeginRequest 和EndRequest 事件的方法。在這兩個方法中,只是簡單的分別打印了一些信息。
下面,在Web.config文件中注冊這個類,就可以使用這個HttpModule了,注冊的方法如下:
<configuration>
<system.web>
<httpModules>
<add name=" MyModule " type=" MyModule, MyModule" />
</httpModules>
</system.web>
</configuration>
現(xiàn)在來看一下效果。編寫一個Aspx頁面test.aspx,內(nèi)容如下:
<%
Response.Write("<h1>This is the Page</h1><hr>");
%>
運行以后的界面如圖所示:
深入研究HttpModule
HttpModule通過對HttpApplication對象的一系列事件的處理來對HTTP處理管道施加影響,這些事件在HttpModule的Init方法中進(jìn)行注冊,包括:
BeginRequest
AuthenticateRequest
AuthorizeRequest
ResolveRequestCache
AcquireRequestState
PreRequestHandlerExecute
PostRequestHandlerExecute
ReleaseRequestState
UpdateRequestCache
EndRequest
其中部分事件同Global.asax中的事件相對應(yīng),對應(yīng)關(guān)系如下:
HttpModule
Global.asax
BeginRequest
Application_BeginRequest
AuthenticateRequest
Application_AuthenticateRequest
EndRequest
Application_EndRequest
在例1中,處理了BeginRequest和EndRequest事件,其他事件的處理方式基本上類似。
同HttpHandler對應(yīng)來看,這些事件,有些在HttpHandler之前發(fā)生,有些在HttpHandler處理完后發(fā)生。了解事件發(fā)生的順序非常重要,因為,服務(wù)器端的對象在不同的時間段有著不同的表現(xiàn)。例子之一是Session的使用。不是所有的事件中都能對Session進(jìn)行處理,而只能在有限的幾個事件中進(jìn)行處理。詳細(xì)的過程可以參考下面的HTTP Request處理生命周期圖。
使用HttpModule實現(xiàn)權(quán)限系統(tǒng)
我們在開發(fā)應(yīng)用系統(tǒng)的時候,應(yīng)用系統(tǒng)的權(quán)限控制是非常重要的一個部分。在ASP中,要實現(xiàn)權(quán)限的控制是比較麻煩的事情,因為我們必須在每個需要控制權(quán)限的ASP頁面中添加權(quán)限控制代碼,從而控制客戶對頁面的訪問。這樣帶來的問題,除了編寫大量重復(fù)代?/span>