萬盛學電腦網

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

ASHX 泛型處理常式 vs ASPX 網頁表單:差異、效能與適用場景完整解析

前言

.ashx (Web Handler) 與 .aspx (Web Form) 同屬 ASP.NET 請求管線,但處理模型截然不同。本文從處理流程、效能、程式碼結構、Session 支援、部署等面向深度比較,協助選型決策。

一、核心差異速查表

特性.ashx (IHttpHandler).aspx (Page)
處理工廠SimpleHandlerFactoryPageHandlerFactory
生命週期僅 ProcessRequest 一個方法完整 Page 生命週期 (Init→Load→Render→Unload)
控制項樹無完整建立、ViewState、事件模型
HTML 輸出手寫 Response.Write宣告式標記 + 伺服器控制項
Session 預設不支援 (需實作 IRequiresSessionState)內建支援
檔案結構單一 .ashx (可搭配 .ashx.cs).aspx + .aspx.cs (CodeBehind)
適用場景圖片動態產生、API 端點、檔案下載、驗證碼、RSS、Sitemap完整網頁、表單輸入、複雜 UI 邏輯
效能輕量、延遲低、記憶體佔用小較重、ViewState、控制項樹開銷

二、最簡單 .ashx 範例

<%@ WebHandler Language="C#" Class="HelloHandler" %>
using System.Web;

public class HelloHandler : IHttpHandler
{
    public bool IsReusable => true; // 無狀態可重用

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain; charset=utf-8";
        context.Response.Write("Hello from ASHX at " + DateTime.Now);
    }
}

無 .cs 代碼後置檔,部署僅需單一檔案;若需編譯保護可改用 CodeBehind 方式。

三、啟用 Session 的 .ashx

public class SessionHandler : IHttpHandler, IRequiresSessionState // 唯讀用 IReadOnlySessionState
{
    public bool IsReusable => false; // 有 Session 狀態不可跨請求重用

    public void ProcessRequest(HttpContext context)
    {
        var count = context.Session["VisitCount"] as int? ?? 0;
        count++;
        context.Session["VisitCount"] = count;
        context.Response.Write($"您是第 {count} 次造訪");
    }
}

四、Web.config Handler Mapping 對照

<system.webServer>
  <handlers>
    <add name="ASMX-WebService" path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory" />
    <add name="ASHX-Handler" path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" />
    <add name="ASPX-Page" path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory" />
  </handlers>
</system.webServer>

SimpleHandlerFactory 直接實例化 IHttpHandler,省略頁面解析、控制項實例化、ViewState 載入/儲存等步驟,理論上回應延遲較低。

五、實戰場景選型指南

選用 .ashx 的情境

  • 輸出非 HTML 內容:圖片 (驗證碼、縮圖)、PDF、Excel、JSON/XML API、RSS、Sitemap、檔案下載。
  • 高頻、低延遲端點:健康檢查、心跳、長輪詢、SignalR 前身的 Comet 端點。
  • 無需頁面生命週期、ViewState、PostBack 的純後端邏輯。

選用 .aspx 的情境

  • 需要完整伺服器控制項 (GridView、Repeater、Validator)、Master Page、主題、使用者控制項。
  • 複雜表單流程、Wizard、多步驟資料輸入。
  • 團隊習慣事件驅動模型 (Btn_Click、Grid_RowCommand)。

六、從 .aspx 遷移至 .ashx 實例:動態圖片產生器

舊版 .aspx:Page_Load 寫入 Response.BinaryWrite,仍會跑完完整生命週期。

新版 .ashx:

public class CaptchaHandler : IHttpHandler
{
    public bool IsReusable => true;
    public void ProcessRequest(HttpContext ctx)
    {
        string code = GenerateRandomCode(4);
        ctx.Session["CaptchaCode"] = code; // 需實作 IRequiresSessionState

        using (Bitmap bmp = new Bitmap(100, 36))
        using (Graphics g = Graphics.FromImage(bmp))
        using (Font font = new Font("Consolas", 20, FontStyle.Bold))
        using (SolidBrush brush = new SolidBrush(Color.Navy))
        {
            g.Clear(Color.AliceBlue);
            g.DrawString(code, font, brush, 5, 2);
            // 加雜訊線...
            ctx.Response.ContentType = "image/png";
            bmp.Save(ctx.Response.OutputStream, ImageFormat.Png);
        }
    }
}

效能提升:去除 ViewState、控制項樹、頁面事件,單次請求 CPU/記憶體降低 60% 以上。

七、常見誤區

  1. 誤以為 .ashx 不能用 Session:實作 IRequiresSessionState 即可 (讀寫) 或 IReadOnlySessionState (唯讀)。
  2. 誤以為 .ashx 無法重用:IsReusable=true 讓同一實例服務多請求,但必須確保執行緒安全 (無成員變數狀態)。
  3. 誤以為 .ashx 只能放在專案根目錄:可置於任意子目錄,URL 對應路徑即可。
copyright © 萬盛學電腦網 all rights reserved