一般處理程式 是相對於 `.aspx` 網頁表單的一種輕量級 HTTP 請求處理機制。它實作 IHttpHandler 介面,直接處理請求與回應,不經過完整的頁面生命週期 (無 Init、Load、Render 等事件),因此效能極高。
Visual Studio 建立 `.ashx` 時會產生兩個檔案:
Handler.ashx:標記檔,指定 `CodeBehind` 與 `Class`Handler.ashx.cs:實作邏輯的 C# 類別<%@ WebHandler Language="C#" Class="web.Handler" %>
// Handler.ashx.cs
using System.Web;
namespace web
{
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable => false; // 是否可跨請求重用,通常為 false
}
}
| 特性 | .aspx 網頁表單 | .ashx 一般處理程式 |
|---|---|---|
| 基底類別 | Page | 無 (實作 IHttpHandler) |
| 生命週期 | 完整 (Init, Load, PreRender, Render...) | 單一 ProcessRequest 方法 |
| ViewState | 支援 | 不支援 |
| 控制項樹 | 完整控制項模型 | 無 |
| 資源消耗 | 較高 | 極低 |
| 適用場景 | 完整 HTML 頁面 | API、檔案下載、圖片處理、AJAX 端點 |
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string referer = context.Request.UrlReferrer?.Host ?? "";
string allowedDomain = "mysite.com";
// 防盜鏈檢查
if (!referer.EndsWith(allowedDomain))
{
context.Response.StatusCode = 403;
context.Response.ContentType = "image/png";
// 輸出預設「防盜鏈」圖片
context.Response.WriteFile("~/Images/hotlink-denied.png");
return;
}
string imagePath = context.Server.MapPath("~/Images/photo.jpg");
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(imagePath);
}
public bool IsReusable => true; // 靜態圖片可重用
}
public class CaptchaHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string code = GenerateCode(4);
context.Session["CaptchaCode"] = code; // 或用分散式快取
using (var bitmap = new Bitmap(100, 36))
using (var g = Graphics.FromImage(bitmap))
using (var ms = new MemoryStream())
{
// 繪製干擾線、文字... (參考前文驗證碼範例)
g.Clear(Color.White);
// ... 繪製邏輯 ...
bitmap.Save(ms, ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(ms.ToArray());
}
}
public bool IsReusable => false;
}
需在 `web.config` 註冊副檔名對應:
<system.webServer>
<handlers>
<add name="ApiHandler" verb="*" path="*.api"
type="MyProject.ApiHandler, MyProject" />
</handlers>
</system.webServer>
public class ApiHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string action = context.Request.PathInfo.TrimStart('/'); // /user/get → user/get
context.Response.ContentType = "application/json";
switch (action.ToLower())
{
case "user/get":
context.Response.Write("{\"id\":1,\"name\":\"張三\"}");
break;
case "user/list":
context.Response.Write("[{\"id\":1},{\"id\":2}]");
break;
default:
context.Response.StatusCode = 404;
context.Response.Write("{\"error\":\"Not Found\"}");
break;
}
}
public bool IsReusable => true;
}
長時間運作的處理程式 (如大檔案轉換、外部 API 呼叫) 應實作非同步介面避免阻塞執行緒池:
public class AsyncHandler : IHttpAsyncHandler
{
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var task = Task.Run(() => DoWork(context));
return task.ContinueWith(t => cb(t));
}
public void EndProcessRequest(IAsyncResult result) { }
public void ProcessRequest(HttpContext context)
{
throw new NotSupportedException("請使用非同步版本");
}
public bool IsReusable => false;
private void DoWork(HttpContext context)
{
// 耗時操作...
context.Response.Write("完成");
}
}
一般處理程式 是 ASP.NET 傳統架構中處理非 HTML 輸出的最佳選擇:效能高、無 ViewState 負擔、部署簡單。掌握其原理與三大經典場景 (圖片處理、驗證碼、自訂 API),能在維護舊系統或特定輕量級需求時遊刃有餘。現代專案建議遷移至 ASP.NET Core Middleware 或 Minimal API 獲得更好的架構支援。