在Asp.net 中HttpHandler,HttpModule,IHttpHandlerFactory的原理與應用(一)中提到,HttpModule會在頁面處理前和後執行,而HttpHandler才是真正的頁面處理。查看C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config,你就會發現裡面有很多關於Httpmodule和httphandler的定義。比方說,httpmodule中定義了在頁面處理前(後)要進行許可權,角色,session等等的檢查和控制,而httphandler則定義了,對於不同的頁面請求(根據尾碼名判斷),執行對應的處理常式.如.aspx, .asmx,.skin等等都有對應的type定義處理常式.
既然httphandler定義了特定頁面請求的處理常式。那麼如果我們自訂httphandler,對於我們定義的頁面,如果client有所請求,將只能按照我們定義的處理常式來處理。(也就是說,我們自訂的處理代替了原來base處理)。
他的應用也是顯見的:比如可以進行資源的許可權控制。如果那些頁面需要一定的許可權才能訪問(比如處在某個IP段),不然就輸出我們自訂的警告資訊; 當然如果client通過url直接存取站內資源,也可以用httphandler控制(如.doc檔案)。
下面是msdn的一個範例:
1.建立處理類
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;
using System.Globalization;
using System.IO;
/**//// <summary>
/// HandlerTest 的摘要描述
/// </summary>
///
namespace HanlderAndModule
...{
public class ImageHandler : IHttpHandler
...{
//
public void ProcessRequest(HttpContext context)
...{
context.Response.Write("<H1>This is an HttpHandler Test.</H1>");
context.Response.Write("<p>Your Browser:</p>");
context.Response.Write("Type: " + context.Request.Browser.Type + "<br>");
context.Response.Write("Version: " + context.Request.Browser.Version);
}
// Override the IsReusable property.
public bool IsReusable
...{
get ...{ return true; }
}
}
}
可以看到,上面自訂實際上實現了IHttpHandler的一個方法:ProcessRequest,一個屬性:IsReusable.實際上請求處理都是在ProcessRequest中處理的.
2.按照一z中所說建立DLL檔案,添加到Bin目錄下
3.配置web.config<httpHandlers>
<add verb="*" path="Default2.aspx" type="HanlderAndModule.ImageHandler,HanlderAndModule"/>
<add verb="*" path="*.Doc" type="HanlderAndModule.ImageHandler,HanlderAndModule"/>
</httpHandlers>
這裡定義了,如果client請求Default2.aspx頁面時,或者直接請求.Doc檔案時,就調用這個自訂的處理常式。
其中的含義:verb指client的請求類別;path指出對什麼頁面調用處理常式;type指出處理常式路徑,定義方法和httmodule一樣。
4.建立幾個doc文檔,建立幾個頁面,運行發現:當訪問Default.aspx, 和XXX/a.doc時,不管你在頁面中做過什麼,頁面只會出現:This is an HttpHandler Test.
Your Browser:
Type: IE6
Version: 6.0
而訪問其他資源,則正常顯示.