IHttpHandler是ASP.NET處理實際操作的介面。在MSDN是這樣定義的:使用自訂的HTTP處理常式同步處理HTTP Web請求而實現的協定。(注意:這裡寫的很清楚是同步HTTP請求如果是非同步話就要使用IHttpAsyncHandler介面程式了)。他包含一個屬性IsReusable用於擷取當前IHttpHandler執行個體是否可用一般設定為True.一個方法ProcessRequest(HttpContext context)進行實際的操作過程。
自訂IHttpHandler
使用自訂的IHttpHandler處理常式需要三步
1)定義一個實現了IHttpHandler介面的類。
2)在Web.config檔案中註冊這個類
3)執行相應的HttpRequst
下面是一個圖片防盜連結的執行個體:
public class LinkProtectHandler: IHttpHandler { #region IHttpHandler 成員 public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { //具體執行的操作 //擷取檔案伺服器端實體路徑 string fileName = context.Server.MapPath(context.Request.FilePath); //如果UrlReferrer為空白則顯示一張預設的禁止盜鏈的圖片 if (context.Request.UrlReferrer.Host==null) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/LinkProtect.jpg"); } else { //如果UrlReferrer中不包含自己網站的主機網域名稱,則顯示一張預設的禁止盜鏈圖片 if (context.Request.UrlReferrer.Host.IndexOf("mydomain.com")>0) { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile(fileName); } else { context.Response.ContentType = "image/JPEG"; context.Response.WriteFile("/LinkProtect.jpg"); } } } #endregion }
Web.Config裡面註冊如下
<httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*.jpeg" validate="false" type="WebApplication3.LinkProtectHandler,WebApplication3"/> </httpHandlers>
自訂IHttpHandlerFactory
IHttpHandlerFactory在MSDN中是這樣定義的:定義類工廠為建立新的IHttpHandler對象而必須實現的協定。他包含2個介面方法,GetHandler():返回實現IHttp介面的類的執行個體。ReleaseHandler():始工廠可以重複使用現有的處理常式執行個體。這個介面就是可以把很多實現IHttpHandler介面的方法放在Factory中在Web.config註冊時主要註冊這個類即可,在使用的時候交由Factory進行判斷到底使用哪個IHttpHandler執行個體。
public class CustomerHttpHandlerFactory:IHttpHandlerFactory { #region IHttpHandlerFactory 成員 public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { //擷取檔案伺服器實體路徑 string path = context.Request.PhysicalPath; //擷取檔案名稱尾碼名 string exstention = Path.GetExtension(path); //進行判斷,交由相應的處理常式 if (exstention==".rss") { return new RssHandler(); } else if (exstention==".atmo") { return new ATMOHandler(); } else { return null; } } public void ReleaseHandler(IHttpHandler handler) { } #endregion }
在Web.Config裡面進行如下定義:
<httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.rss,*.atom" validate="false" type="WebApplication3.CustomerHttpHandlerFactory,WebApplication3"/> </httpHandlers>
IHttpAsyncHandler非同步介面
IHttpAsyncHandler在MSDN中是這樣描述的:定義 HTTP 非同步處理常式對象必須實現的協定。他包含3個方法:
BeginProcessRequest:啟動對 HTTP 處理常式的非同步呼叫,EndProcessRequest:進程結束時提供非同步處理 End 方法。ProcessRequest:通過實現 IHttpHandler 介面的自訂 HttpHandler 啟用 HTTP Web 請求的處理。 (繼承自 IHttpHandler。)和一個IsReusable屬性。