萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> .NET 程式設計

ASP.NET 核心管道架構揭密:從 IIS 接收請求到 HttpHandler 處理的完整流程

為什麼要理解 HTTP 請求處理流程?

知其然更要知其所以然。掌握 IIS、ASP.NET Runtime、HttpApplication、Module、Handler 協作細節,能精準排查效能瓶頸、安全漏洞、生命週期事件順序錯誤等疑難雜症。

階段一:IIS 接收與分派 (ISAPI 對應)

  1. HTTP.sys 核心模式驅動程式監聽埠 80/443,依 URL 前綴路由至應用程式集區
  2. Worker Process (w3wp.exe / aspnet_wp.exe) 啟動
  3. IIS 依副檔名對應 ISAPI 擴展:.aspx → aspnet_isapi.dll (IIS 6/7 經典模式)
  4. IIS 7+ 整合模式:Managed Handler 直接註冊於 system.webServer/handlers,無 ISAPI 跳板

關鍵設定:「確認檔案是否存在」 核取方塊控制 URL Rewrite/虛擬路徑是否觸發 404。

階段二:ASP.NET Runtime 載入與 HttpRuntime

  • ISAPI 將請求封裝為 HttpWorkerRequest
  • 在隔離的 AppDomain 中載入 HttpRuntime
  • 呼叫 HttpRuntime.ProcessRequest(HttpWorkerRequest)
  • HttpRuntime 擁有請求的所有資訊:URL、QueryString、Headers、ServerVariables

階段三:HTTP 管道 — Module 與 Handler

HTTP Pipeline

流程步驟

  1. HttpApplication 建立:代表應用程式實例,建立 HttpContext (含 Request、Response、Session、User、Cache、Items)
  2. 模組管道:請求依序通過註冊的 IHttpModule (如 FormsAuthenticationModule, SessionStateModule, UrlRoutingModule)
    模組可:攔截、修改、短路請求 (如驗證失敗直接 Response.End())
  3. Handler 執行:IHttpHandler 處理實際邏輯
    Page 實作 IHttpHandler,.aspx 頁面即 Handler
    MVC 中 MvcHandler 處理路由後的 Controller 執行
  4. 模組返程:請求回傳時再次通過模組 (如 EndRequest 事件),執行清理、壓縮、記錄日誌

為什麼有成對事件 (Inserting/Inserted)?

對應管道「去程/返程」:
Executing (Handler 前) → Executed (Handler 後)
Inserting (資料源操作前) → Inserted (操作後)

關鍵類別關係圖

HttpContext (Current)
  ├─ HttpRequest (輸入)
  ├─ HttpResponse (輸出)
  ├─ HttpSessionState (Session)
  ├─ HttpApplicationState (Application)
  ├─ IPrincipal User (身份)
  └─ IDictionary Items (請求級資料共享)

HttpApplication (每請求一實例,池化複用)
  ├─ Events: BeginRequest, AuthenticateRequest, AuthorizeRequest, ...
  ├─ Modules 集合 (IHttpModule)
  └─ Handler (IHttpHandler) → Page / MvcHandler / Ashx / 自訂

IHttpHandler
  └─ ProcessRequest(HttpContext) → 單一入口點

實戰除錯技巧

  • Global.asax 事件順序即管道順序,可注入日誌追蹤
  • 自訂 IHttpModule 記錄請求耗時、參數、例外
  • HttpContext.Current.Items 跨模組/Handler 傳遞資料 (請求生命週期)
  • 管道模式切換:IIS 管理器 → 應用程式集區 → 基本設定 → 「整合/經典」

現代化演進:ASP.NET Core Middleware

ASP.NET Core 移除 HttpModule/Handler,改以 Middleware Pipeline 取代:

app.Use(async (context, next) => {
    // Before next (相當於 Module 去程)
    await next();
    // After next (相當於 Module 返程)
});
app.Map("/api", api => api.UseMiddleware()); // 相當於 Handler 映射

概念一脈相承:管道、中介軟體、終端處理器。

copyright © 萬盛學電腦網 all rights reserved