.ashx (Web Handler) 與 .aspx (Web Form) 同屬 ASP.NET 請求管線,但處理模型截然不同。本文從處理流程、效能、程式碼結構、Session 支援、部署等面向深度比較,協助選型決策。
| 特性 | .ashx (IHttpHandler) | .aspx (Page) |
|---|---|---|
| 處理工廠 | SimpleHandlerFactory | PageHandlerFactory |
| 生命週期 | 僅 ProcessRequest 一個方法 | 完整 Page 生命週期 (Init→Load→Render→Unload) |
| 控制項樹 | 無 | 完整建立、ViewState、事件模型 |
| HTML 輸出 | 手寫 Response.Write | 宣告式標記 + 伺服器控制項 |
| Session 預設 | 不支援 (需實作 IRequiresSessionState) | 內建支援 |
| 檔案結構 | 單一 .ashx (可搭配 .ashx.cs) | .aspx + .aspx.cs (CodeBehind) |
| 適用場景 | 圖片動態產生、API 端點、檔案下載、驗證碼、RSS、Sitemap | 完整網頁、表單輸入、複雜 UI 邏輯 |
| 效能 | 輕量、延遲低、記憶體佔用小 | 較重、ViewState、控制項樹開銷 |
<%@ 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 方式。
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} 次造訪");
}
}
<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 載入/儲存等步驟,理論上回應延遲較低。
舊版 .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% 以上。
IRequiresSessionState 即可 (讀寫) 或 IReadOnlySessionState (唯讀)。IsReusable=true 讓同一實例服務多請求,但必須確保執行緒安全 (無成員變數狀態)。