首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 使用 HttpModule 計算頁面執行時間

     編輯:ASP.NET 基礎

前言

HttpModule 是 ASP.NET 管線中的攔截器,可在請求生命週期的各個階段插入自訂邏輯。本文示範如何建立一個 HttpModule,在 BeginRequest 記錄開始時間、在 EndRequest 計算經過時間並輸出至頁面底部,達到全站監控頁面執行效能的目的。

建立 HttpModule 類別

using System;
using System.Web;

namespace TimerHttpModule
{
    public class TimerModule : IHttpModule
    {
        private DateTime _startTime;

        public void Init(HttpApplication application)
        {
            // 訂閱請求開始與結束事件
            application.BeginRequest += OnBeginRequest;
            application.EndRequest += OnEndRequest;
        }

        private void OnBeginRequest(object sender, EventArgs e)
        {
            _startTime = DateTime.Now;
        }

        private void OnEndRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;
            var context = application.Context;
            var elapsed = DateTime.Now - _startTime;
            
            // 將執行時間寫入回應串流
            context.Response.Write($"

頁面執行時間:{elapsed.TotalMilliseconds:F2} ms

"); } public void Dispose() { } } }

在 Web.config 中註冊

IIS 6 / Classic 模式:

<configuration>
  <system.web>
    <httpModules>
      <add name="TimerModule" type="TimerHttpModule.TimerModule" />
    </httpModules>
  </system.web>
</configuration>

IIS 7+ / Integrated 模式:

<configuration>
  <system.webServer>
    <modules>
      <add name="TimerModule" type="TimerHttpModule.TimerModule" />
    </modules>
  </system.webServer>
</configuration>

潛在問題與解決方案

直接在 Response.Write 輸出會影響所有回應,包括:

  • Web Services (ASMX / WCF)
  • Generic Handlers (.ashx)
  • 輸出 JSON/XML 的 .aspx 頁面
  • 圖片、CSS、JS 等靜態資源(若經由 ASP.NET 處理)

方案一:依 URL 過濾

private void OnEndRequest(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;
    var ctx = app.Context;
    
    // 僅對 HTML 頁面輸出
    if (ctx.Request.Path.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase) &&
        ctx.Response.ContentType.Equals("text/html", StringComparison.OrdinalIgnoreCase))
    {
        var elapsed = DateTime.Now - _startTime;
        ctx.Response.Write($"

頁面執行時間:{elapsed.TotalMilliseconds:F2} ms

"); } }

方案二:輸出為 HTTP Header(推薦)

private void OnEndRequest(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;
    var ctx = app.Context;
    var elapsed = DateTime.Now - _startTime;
    
    // 不汙染回應內容,前端可透過 JS 讀取或開發者工具查看
    ctx.Response.Headers["X-Page-Execution-Time"] = $"{elapsed.TotalMilliseconds:F2} ms";
}

進階應用

  • 搭配 MiniProfiler 或 Glimpse 進行更詳細的效能分析。
  • 將執行時間寫入 Log(Serilog、NLog)供事後分析。
  • 區分「伺服器處理時間」與「資料庫查詢時間」,精準定位瓶頸。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved