ASP.NET 請求處理管線起點是 HttpModule。本文對比 ASP 與 ASP.NET 請求處理架構,詳細闡述 HttpRuntime → HttpApplicationFactory → HttpModule → HttpHandlerFactory → HttpHandler 的完整流程,並示範如何實作自訂 Module 實現驗證、日誌、重寫、壓縮等橫切關注點。
| 特性 | ASP (經典) | ASP.NET |
|---|---|---|
| 處理程式 | asp.dll (ISAPI Extension) | aspnet_isapi.dll → Managed Pipeline |
| 執行模式 | 進程內 (inetinfo.exe) / 進程外 | Worker Process (w3wp.exe) 託管 CLR |
| 解析方式 | 直譯執行,每請求重新解析 | 編譯為 IL → JIT → 機器碼,快取組件 |
| 擴展機制 | COM 組件、ISAPI Filter | HttpModule / HttpHandler (Managed Code) |
| 狀態管理 | Session 靠 Cookie/URL,進程內易丟失 | Session State Service / SQL / Redis,跨進程共享 |
HttpContext (包裝 HttpRequest/HttpResponse)。HttpApplication 實例 (對應 Global.asax 類別)。BeginRequest, AuthenticateRequest, AuthorizeRequest...)。PageHandlerFactory)。

public class CustomAuthModule : IHttpModule
{
public void Init(HttpApplication context)
{
// 掛載事件 (按管線順序)
context.AuthenticateRequest += OnAuthenticateRequest;
context.AuthorizeRequest += OnAuthorizeRequest;
context.BeginRequest += OnBeginRequest; // 重寫/重導
context.EndRequest += OnEndRequest; // 壓縮/日誌
}
private void OnAuthenticateRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// 自訂驗證邏輯:檢查 Token、JWT、SSO Cookie
// app.Context.User = new GenericPrincipal(...);
}
private void OnAuthorizeRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// URL 權限檢查,失敗 → 401/403/導向登入
}
private void OnBeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// URL 重寫、封鎖 IP、強制 HTTPS
}
private void OnEndRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
// GZip/Deflate 壓縮回應
// 記錄存取日誌 (請求耗時、狀態碼、用戶)
}
public void Dispose() { /* 清理資源 */ }
}
<system.webServer> <!-- IIS 7+ Integrated -->
<modules>
<add name="CustomAuth" type="MyApp.CustomAuthModule" preCondition="integratedMode" />
</modules>
</system.webServer>
<system.web> <!-- IIS 6 / Classic -->
<httpModules>
<add name="CustomAuth" type="MyApp.CustomAuthModule" />
</httpModules>
</system.web>
BeginRequestAuthenticateRequestPostAuthenticateRequestAuthorizeRequestPostAuthorizeRequestResolveRequestCache (輸出快取)PostResolveRequestCacheMapRequestHandler (決定 Handler)PostMapRequestHandlerAcquireRequestState (Session 載入)PostAcquireRequestStatePreRequestHandlerExecutePostRequestHandlerExecuteReleaseRequestState (Session 儲存)PostReleaseRequestStateUpdateRequestCache (存入輸出快取)PostUpdateRequestCacheEndRequestHttpModule 是 ASP.NET 管線的**橫切關注點實現者**:驗證、授權、重寫、壓縮、日誌、追蹤、防 CSRF、CORS... 皆以模組形式掛載,**不侵入業務邊碼**。掌握管線事件順序、HttpApplication 生命週期、模組註冊差異 (Integrated vs Classic),是進階 ASP.NET 開發者的必修課。下一站:IHttpHandler 處理終點邏輯。