ASP.NET 管線事件由 HttpApplication 暴露,處理方式有二:IHttpModule 與 Global.asax,核心皆為 IHttpModule 介面。
public interface IHttpModule {
void Dispose();
void Init(HttpApplication context);
}
Dispose:釋放非託管資源。Init:接收 HttpApplication 實例,註冊管線事件(如 context.PostAuthenticateRequest += ...)。實作類別需於 web.config <httpModules> 註冊方生效。
請求真正處理發生於 PreRequestHandlerExecute 與 PostRequestHandlerExecute 之間。HttpApplication 為管道提供預處理/後處理統一機制。
所有處理常式必須實作 IHttpHandler(同步)或 IHttpAsyncHandler(非同步):
public interface IHttpHandler {
void ProcessRequest(HttpContext context);
bool IsReusable { get; }
}
ProcessRequest:核心處理邏輯,透過 context.Response 輸出結果。IsReusable:指示實例是否可快取重用。處理常式與請求的對應關係於 web.config <httpHandlers> 設定(副檔名對應)。Page 類別即實作 IHttpHandler,是最常見的處理常式。