將通用處理邏輯(如圖片產生、檔案下載、API 端點)封裝於類別庫的 IHttpHandler 實作中,可跨專案重用並保持主專案乾淨。本文示範建立 Handler 類別、編譯為 DLL、於主站 web.config 註冊的完整流程。
// EdiBlog.Core.Web.HttpHandlers.ExampleHandler.cs
namespace EdiBlog.Core.Web.HttpHandlers
{
using System;
using System.Web;
public class ExampleHandler : IHttpHandler
{
public bool IsReusable => false; // 若無狀態可設 true 提升效能
public void ProcessRequest(HttpContext context)
{
// 您的邏輯:產生圖驗證碼、輸出動態圖片、處理 AJAX 請求等
context.Response.ContentType = "text/plain";
context.Response.Write("Hello from Class Library Handler!");
}
}
}
IHttpHandler 介面,必須實作 IsReusable 與 ProcessRequest。EdiBlog.Core.dll。<configuration>
<system.webServer>
<handlers>
<add name="ExampleHandler"
verb="*"
path="ex.axd"
type="EdiBlog.Core.Web.HttpHandlers.ExampleHandler, EdiBlog.Core" />
</handlers>
</system.webServer>
</configuration>
| 屬性 | 說明 |
|---|---|
name | 唯一識別名稱 |
verb | HTTP 動詞,* 表全部 |
path | 對應 URL 路徑,副檔名需 IIS 支援(如 .axd、.ashx、.json) |
type | 完整類別名稱, 組件名稱(不含副檔名) |
<system.web>
<httpHandlers>
<add verb="*" path="ex.axd" type="EdiBlog.Core.Web.HttpHandlers.ExampleHandler, EdiBlog.Core" />
</httpHandlers>
</system.web>
.axd、.ashx、.soap 等),避免需額外設定 MIME 對應。web.config 覆寫,上述設定即可生效。public abstract class BaseHandler : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
// 共用前置處理:記錄、驗證、設定回應標頭
HandleRequest(context);
}
protected abstract void HandleRequest(HttpContext context);
}
具體 Handler 繼承 BaseHandler 實作 HandleRequest,集中管理共用邏輯。
ProcessRequest(傳入 Mock HttpContext)。