ASP.NET 請求處理管線 是理解中介軟、URL 重寫、認證授權、壓縮、日誌攔截等核心機制的基礎。本文系統梳理 IIS 7+ 整合模式下的管線階段、`HttpModule` 事件訂閱、`HttpHandler` 對應規則、自訂模組/處理常式開發、與 `web.config` 註冊差異。
BeginRequest → AuthenticateRequest → AuthorizeRequest → ResolveRequestCache
→ AcquireRequestState → PreRequestHandlerExecute → **ExecuteHandler** (HttpHandler.ProcessRequest)
→ PostRequestHandlerExecute → ReleaseRequestState → UpdateRequestCache → LogRequest → EndRequest
每個階段對應 `HttpApplication` 事件,`HttpModule` 可訂閱任意階段攔截請求/回應。
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() { }
}
<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>
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>
實作 `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) { }
}
註冊:`
| 特性 | HttpModule | HttpHandler |
|---|---|---|
| 介面 | IHttpModule | IHttpHandler |
| 參與階段 | 管線所有事件 | 僅 ExecuteHandler 階段 |
| 數量 | 多個模組串聯 | 單一請求對應一個 Handler |
| 典型用途 | 認證、日誌、壓縮、重寫、Session 管理 | .aspx、.asmx、.ashx、靜態檔、自訂端點 |
| 註冊節點 | <modules> | <handlers> |
| 覆蓋關係 | 累加 (可移除內建) | 覆蓋 (同 path/verb 後註冊勝出) |
Core 中管線由 `RequestDelegate` 中介軟體組成,對應關係:
深入掌握管線階段與 Module/Handler 邊界,是排查 ASP.NET 請求流程異常、實作跨領域關注點 (AOP) 的關鍵能力。