首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 底層機制 (上) HttpModule:管線事件攔截與橫切關注點實現

     編輯:關於ASP.NET

ASP.NET 請求處理管線起點是 HttpModule。本文對比 ASP 與 ASP.NET 請求處理架構,詳細闡述 HttpRuntime → HttpApplicationFactory → HttpModule → HttpHandlerFactory → HttpHandler 的完整流程,並示範如何實作自訂 Module 實現驗證、日誌、重寫、壓縮等橫切關注點。

ASP vs ASP.NET 請求處理架構對比

特性ASP (經典)ASP.NET
處理程式asp.dll (ISAPI Extension)aspnet_isapi.dll → Managed Pipeline
執行模式進程內 (inetinfo.exe) / 進程外Worker Process (w3wp.exe) 託管 CLR
解析方式直譯執行,每請求重新解析編譯為 IL → JIT → 機器碼,快取組件
擴展機制COM 組件、ISAPI FilterHttpModule / HttpHandler (Managed Code)
狀態管理Session 靠 Cookie/URL,進程內易丟失Session State Service / SQL / Redis,跨進程共享

Managed Pipeline 請求處理完整流程

  1. HttpRuntime.ProcessRequest:進入點,建立 HttpContext (包裝 HttpRequest/HttpResponse)。
  2. HttpApplicationFactory.GetApplicationInstance:從池取得或建立 HttpApplication 實例 (對應 Global.asax 類別)。
  3. HttpApplication.Init:初始化模組集合,**掛載 HttpModule 事件** (如 BeginRequest, AuthenticateRequest, AuthorizeRequest...)。
  4. 依序觸發 Pipeline 事件 (20+ 事件),每個事件通知所有註冊模組。
  5. HttpHandlerFactory.GetHandler:解析 Handler (如 PageHandlerFactory)。
  6. Handler.ProcessRequest:執行頁面/服務邏輯,生成回應。
  7. EndRequest 事件:模組收尾 (日誌、清理、壓縮輸出)。
  8. HttpApplication 歸還池:供下一請求複用。

ASP 請求處理 ASP.NET 請求處理

自訂 HttpModule 實作範本

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() { /* 清理資源 */ }
}

註冊模組 (web.config)

<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>

核心管線事件順序 (常用)

  1. BeginRequest
  2. AuthenticateRequest
  3. PostAuthenticateRequest
  4. AuthorizeRequest
  5. PostAuthorizeRequest
  6. ResolveRequestCache (輸出快取)
  7. PostResolveRequestCache
  8. MapRequestHandler (決定 Handler)
  9. PostMapRequestHandler
  10. AcquireRequestState (Session 載入)
  11. PostAcquireRequestState
  12. PreRequestHandlerExecute
  13. Handler.Execute (ProcessRequest)
  14. PostRequestHandlerExecute
  15. ReleaseRequestState (Session 儲存)
  16. PostReleaseRequestState
  17. UpdateRequestCache (存入輸出快取)
  18. PostUpdateRequestCache
  19. EndRequest

結語

HttpModule 是 ASP.NET 管線的**橫切關注點實現者**:驗證、授權、重寫、壓縮、日誌、追蹤、防 CSRF、CORS... 皆以模組形式掛載,**不侵入業務邊碼**。掌握管線事件順序、HttpApplication 生命週期、模組註冊差異 (Integrated vs Classic),是進階 ASP.NET 開發者的必修課。下一站:IHttpHandler 處理終點邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved