萬盛學電腦網

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

ASP.NET HTTP 模組與處理常式 (HttpModule、HttpHandler) 架構深度解析

ASP.NET 請求處理管線 是理解中介軟、URL 重寫、認證授權、壓縮、日誌攔截等核心機制的基礎。本文系統梳理 IIS 7+ 整合模式下的管線階段、`HttpModule` 事件訂閱、`HttpHandler` 對應規則、自訂模組/處理常式開發、與 `web.config` 註冊差異。

請求處理管線階段 (IIS 7+ Integrated Mode)

BeginRequest → AuthenticateRequest → AuthorizeRequest → ResolveRequestCache
→ AcquireRequestState → PreRequestHandlerExecute → **ExecuteHandler** (HttpHandler.ProcessRequest)
→ PostRequestHandlerExecute → ReleaseRequestState → UpdateRequestCache → LogRequest → EndRequest

每個階段對應 `HttpApplication` 事件,`HttpModule` 可訂閱任意階段攔截請求/回應。

HttpModule 開發與註冊

實作 IHttpModule

public class RequestLogModule : IHttpModule {
    public void Init(HttpApplication context) {
        context.BeginRequest += OnBeginRequest;
        context.EndRequest += OnEndRequest;
        context.Error += OnError;
    }

    private void OnBeginRequest(object sender, EventArgs e) {
        var app = (HttpApplication)sender;
        var ctx = app.Context;
        Log.Debug($"→ {ctx.Request.HttpMethod} {ctx.Request.RawUrl} from {ctx.Request.UserHostAddress}");
    }

    private void OnEndRequest(object sender, EventArgs e) {
        var app = (HttpApplication)sender;
        Log.Debug($"← {app.Context.Response.StatusCode} {app.Context.Response.ContentType}");
    }

    private void OnError(object sender, EventArgs e) {
        var ex = ((HttpApplication)sender).Server.GetLastError();
        Log.Error(ex, "未處理例外");
    }

    public void Dispose() { }
}

web.config 註冊 (IIS 7+ Integrated)

<system.webServer>
  <modules>
    <add name="RequestLogModule" type="MyApp.Modules.RequestLogModule, MyApp" preCondition="managedHandler" />
    <remove name="FormsAuthentication" /> <!-- 移除內建模組 -->
  </modules>
</system.webServer>

<!-- 傳統模式 (舊版 IIS 6 相容) -->
<system.web>
  <httpModules>
    <add name="RequestLogModule" type="MyApp.Modules.RequestLogModule, MyApp" />
  </httpModules>
</system.web>

HttpHandler 開發與對應

實作 IHttpHandler

public class ImageWatermarkHandler : IHttpHandler {
    public bool IsReusable => true;

    public void ProcessRequest(HttpContext context) {
        string imagePath = context.Server.MapPath("~/Images/" + context.Request.QueryString["img"]);
        if (!File.Exists(imagePath)) { context.Response.StatusCode = 404; return; }

        using (var img = Image.FromFile(imagePath))
        using (var g = Graphics.FromImage(img))
        using (var font = new Font("Arial", 12))
        using (var brush = new SolidBrush(Color.FromArgb(128, 255, 255, 255))) {
            g.DrawString("© Watermark", font, brush, 10, 10);
            context.Response.ContentType = "image/jpeg";
            img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
    }
}

路由對應註冊

<system.webServer>
  <handlers>
    <add name="Watermark" verb="GET" path="watermark.axd" 
         type="MyApp.Handlers.ImageWatermarkHandler, MyApp" preCondition="integratedMode" />
    <add name="CustomAspx" verb="*" path="*.myx" 
         type="System.Web.UI.PageHandlerFactory" preCondition="integratedMode" />
  </handlers>
</system.webServer>

HttpHandlerFactory 進階調度

實作 `IHttpHandlerFactory` 依請求動態決定回傳哪個 Handler:

public class DynamicHandlerFactory : IHttpHandlerFactory {
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) {
        if (url.Contains("/api/")) return new ApiHandler();
        if (url.EndsWith(".rpt")) return new ReportHandler();
        return new PageHandlerFactory().GetHandler(context, requestType, url, pathTranslated);
    }
    public void ReleaseHandler(IHttpHandler handler) { }
}

註冊:`` (需置於最後,作為 fallback)。

Module vs Handler 關鍵差異

特性HttpModuleHttpHandler
介面IHttpModuleIHttpHandler
參與階段管線所有事件僅 ExecuteHandler 階段
數量多個模組串聯單一請求對應一個 Handler
典型用途認證、日誌、壓縮、重寫、Session 管理.aspx、.asmx、.ashx、靜態檔、自訂端點
註冊節點<modules><handlers>
覆蓋關係累加 (可移除內建)覆蓋 (同 path/verb 後註冊勝出)

遷移至 ASP.NET Core Middleware

Core 中管線由 `RequestDelegate` 中介軟體組成,對應關係:

  • `HttpModule` → `IMiddleware` / `app.Use(async (ctx, next) => { ... })`
  • `HttpHandler` → `app.MapGet/Post/Run` / `app.UseEndpoints`
  • `HttpHandlerFactory` → 路由匹配 / `MapWhen`

深入掌握管線階段與 Module/Handler 邊界,是排查 ASP.NET 請求流程異常、實作跨領域關注點 (AOP) 的關鍵能力。

copyright © 萬盛學電腦網 all rights reserved