在我們 .NET web.config 的設定檔中經常會看到HttpHandler與HttpModule這兩個詞,那麼你真正理解這兩個詞嗎?下面就給大家講解一下HttpHandler、HttpModule的作用和應用。
什麼是IHttpHandler?
IHttpHandler定義了實現HTTP請求的一些基本約定,簡單理解就是配置一個HttpHandler就實現了一個URL請求。如果一個IHttpHandler定義了其實作類別,那麼就相當於是覆蓋關係。
IHttpHandler的使用方法
HttpHandler,則需要繼承自IHttpHandler介面,如下面的代碼:
public class SampleHttpHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("SampleHttpHandler返回的結果!");
}
}
SampleHttpHandler繼承自IHttpHandler介面,介面中有一個需要實現的方法ProcessRequest,這個方法就是具體處理的內容。
當cs代碼寫好後只需要配置web.config即可,如下所示:
<add verb="*" path="/SampleHttpHandler" type="Sample.SampleHttpHandler"/>
這樣SampleHttpHandler就是配置成功了,”/SampleHttpHandler”就是可以訪問的路徑了。
什麼是HttpModule?
簡單說HttpModule就是一個過濾器。任何一個HTTP請求在做任何處理前都必須經過HttpModule的處理,HttpModule就是HTTP請求的必經之路。其工作原理就是監聽HttpRequest,對請求做統一吃處理,比如可以處理將所有為以”/”結尾的url重新導向到以”/”結尾的URL中。
HttpModule的使用方法
HttpModule都必須實現IHttpModule介面,在實作類別中做具體的處理。
比如下面的例子:
<httpModules>
<add name="SampleHttpModule" type="Sample.SampleHttpModule,Sample"/>
</httpModules>
只要將SampleHttpModule完整空間路徑配置正確即可。
下面的圖反應了HttpHandler、HttpModule的關係
到此你應該明白HttpHandler、HttpModule的區別和什麼時候用HttpHandler,什麼時候用HttpModule。將HttpHandler比作完整工藝流程,那麼HttpModule負責的則是流程中的一個環節。