在效能調優、SLA 監控、除錯分析場景中,精確測量每個 `.aspx` 頁面的伺服器端執行時間至關重要。本文示範如何實作自訂 `IHttpHandler` 攔截所有 `.aspx` 請求,包裝原始處理器並在 `ProcessRequest` 前後計時,將耗時資訊直接寫入回應,零侵入式達成全站效能可視化。
using System;
using System.Web;
using System.Web.UI;
using System.Web.SessionState;
namespace Cuyahoga.Web.HttpHandlers
{
public class PageHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string rawUrl = context.Request.RawUrl;
DateTime startTime = DateTime.Now;
// 解析 .aspx 實際路徑 (排除 QueryString)
string aspxPagePath = rawUrl.Substring(0, rawUrl.IndexOf(".aspx") + 5);
// 取得編譯後的頁面實例 (原始處理器)
IHttpHandler handler = PageParser.GetCompiledPageInstance(
aspxPagePath, null, context);
// 執行原始頁面邏輯
handler.ProcessRequest(context);
// 計算並輸出耗時
TimeSpan duration = DateTime.Now - startTime;
context.Response.Write(
String.Format("Request finished. Total duration: {0} ms.",
duration.TotalMilliseconds));
}
public bool IsReusable => true;
}
}
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.aspx"
type="Cuyahoga.Web.HttpHandlers.PageHandler, Cuyahoga.Web" />
</httpHandlers>
</system.web>
</configuration>
注意:IIS 7+ 整合管道模式需改註冊至 `
| 增強 | 實作要點 |
|---|---|
| 結構化日誌 | 輸出 JSON 至檔案/ELK/Seq,包含 URL、User、Duration、StatusCode |
| 閾值告警 | `if (duration.TotalSeconds > 5) AlertService.Notify(...)` |
| 區段計時 | 在頁面 `Page_Init`、`Page_Load`、`Page_Render` 埋點,細化瓶頸定位 |
| 非同步支援 | 實作 `IHttpAsyncHandler`,配合 `BeginProcessRequest`/`EndProcessRequest` |
| 排除靜態資源 | 路徑判斷排除 `.axd`、`.ashx`、SignalR 等特殊端點 |
此模式展示了 ASP.NET HTTP 管線的強大擴充性:**HttpHandler 作為請求處理的入口,攔截、包裝、委派、觀測**,是 AOP 在 Web 層的經典實踐。