萬盛學電腦網

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

ASP.NET 透過 IHttpModule 實作全站頁面執行時間監控

前言

效能監控是維持系統健康的關鍵。在 ASP.NET 中,實作自訂 IHttpModule 可在不修改任何現有頁面代碼的前提下,自動為所有輸出 HTML 的頁面附加執行時間資訊。

核心實作:PerformanceMonitorModule

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() { } }

註冊模組

IIS 7+ 整合模式

<system.webServer>
  <modules>
    <add name="PerformanceMonitor" type="YourNamespace.PerformanceMonitorModule" />
  </modules>
</system.webServer>

IIS 6 / 傳統模式

<system.web>
  <httpModules>
    <add name="PerformanceMonitor" type="YourNamespace.PerformanceMonitorModule" />
  </httpModules>
</system.web>

運作原理解析

  1. PreRequestHandlerExecute:頁面處理器(.aspx/.ashx/MVC Controller)開始執行前觸發,建立 Stopwatch 存入 HttpContext.Items。
  2. PostRequestHandlerExecute:處理器執行完畢觸發,取出 Stopwatch 計算經過時間。
  3. 透過 HttpContext.Items 傳遞計時器,生命週期限於單一請求,執行緒安全。
  4. 檢查 ContentType == "text/html" 避免汙染 JSON、圖片、檔案下載等非 HTML 回應。

進階擴充建議

  • 記錄至日誌:搭配 NLog/Serilog 記錄 Url、ElapsedMs、UserAgent、StatusCode,供離線分析。
  • 慢頁面告警:超過閾值(如 2 秒)寫入警告日誌或發送通知。
  • 區分階段計時:在 Page_Init、Page_Load、Page_Render 分別埋點,定位瓶頸階段。
  • 生產環境開關:透過 Web.config appSettings 控制是否啟用,避免效能影響。

注意事項

  • Stopwatch 精度高於 DateTime.Now,適合毫秒級計時。
  • 模組執行順序:若有其他模組修改 Response.Filter,確保本模組在最後輸出,或使用 Response.Filter 包裝方式注入。
  • MVC/Core 專案建議改用 Middleware 或 ActionFilter 實現同樣功能。

結語

一個不到 50 行的 IHttpModule,即可為全站帶來零侵入式的執行時間可見性。這是「可觀測性」建設的最小可行性起點,建議所有 ASP.NET 專案標準化部署。

copyright © 萬盛學電腦網 all rights reserved