效能監控是維持系統健康的關鍵。在 ASP.NET 中,實作自訂 IHttpModule 可在不修改任何現有頁面代碼的前提下,自動為所有輸出 HTML 的頁面附加執行時間資訊。
using System;
using System.Diagnostics;
using System.Web;
public class PerformanceMonitorModule : IHttpModule {
public void Init(HttpApplication context) {
// 請求進入處理器前:啟動計時器
context.PreRequestHandlerExecute += (sender, e) => {
var app = (HttpApplication)sender;
var timer = new Stopwatch();
app.Context.Items["PageTimer"] = timer;
timer.Start();
};
// 處理器執行完成後:停止計時並輸出
context.PostRequestHandlerExecute += (sender, e) => {
var app = (HttpApplication)sender;
var ctx = app.Context;
var timer = (Stopwatch)ctx.Items["PageTimer"];
if (timer == null) return;
timer.Stop();
// 僅對 HTML 回應輸出,避免干擾 API/圖片/下載
if (ctx.Response.ContentType == "text/html") {
double seconds = (double)timer.ElapsedTicks / Stopwatch.Frequency;
string msg = string.Format("{0:F4} sec", seconds);
RenderTimer(ctx.Response, msg);
}
};
}
private void RenderTimer(HttpResponse response, string elapsed) {
response.Write("");
response.Write("Page Generated in " + elapsed + "");
response.Write("");
}
public void Dispose() { }
}
<system.webServer>
<modules>
<add name="PerformanceMonitor" type="YourNamespace.PerformanceMonitorModule" />
</modules>
</system.webServer>
<system.web>
<httpModules>
<add name="PerformanceMonitor" type="YourNamespace.PerformanceMonitorModule" />
</httpModules>
</system.web>
PreRequestHandlerExecute:頁面處理器(.aspx/.ashx/MVC Controller)開始執行前觸發,建立 Stopwatch 存入 HttpContext.Items。PostRequestHandlerExecute:處理器執行完畢觸發,取出 Stopwatch 計算經過時間。HttpContext.Items 傳遞計時器,生命週期限於單一請求,執行緒安全。ContentType == "text/html" 避免汙染 JSON、圖片、檔案下載等非 HTML 回應。Url、ElapsedMs、UserAgent、StatusCode,供離線分析。Page_Init、Page_Load、Page_Render 分別埋點,定位瓶頸階段。Web.config appSettings 控制是否啟用,避免效能影響。Stopwatch 精度高於 DateTime.Now,適合毫秒級計時。Response.Filter,確保本模組在最後輸出,或使用 Response.Filter 包裝方式注入。一個不到 50 行的 IHttpModule,即可為全站帶來零侵入式的執行時間可見性。這是「可觀測性」建設的最小可行性起點,建議所有 ASP.NET 專案標準化部署。