.ashx 不僅能輸出純文字,透過設定 Content-Type 可偽裝成圖片、JavaScript、CSS、XML 等任何 MIME 類型,實現動態資源輸出。本文彙整五大實戰模式,並解決 Session 存取、快取控制、錯誤處理等關鍵細節。
<%@ WebHandler Language="C#" Class="PhotoHandler" %>
using System;
using System.IO;
using System.Web;
public class PhotoHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext ctx)
{
// 1. 解析參數
string idStr = ctx.Request.QueryString["PhotoID"];
string albumStr = ctx.Request.QueryString["AlbumID"];
string sizeKey = ctx.Request.QueryString["Size"] ?? "O"; // S/M/L/O
if (string.IsNullOrEmpty(idStr) && string.IsNullOrEmpty(albumStr))
{
ctx.Response.StatusCode = 400;
ctx.Response.End();
return;
}
// 2. 取得圖片串流 (假設 PhotoManager 為資料存取層)
Stream stream = null;
if (!string.IsNullOrEmpty(idStr))
stream = PhotoManager.GetPhoto(int.Parse(idStr), ParseSize(sizeKey));
else
stream = PhotoManager.GetFirstPhoto(int.Parse(albumStr), ParseSize(sizeKey));
if (stream == null) stream = PhotoManager.GetPlaceholder(ParseSize(sizeKey));
// 3. 輸出
ctx.Response.ContentType = "image/jpeg";
ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
ctx.Response.Cache.SetMaxAge(TimeSpan.FromDays(30)); // 瀏覽器快取 30 天
ctx.Response.BufferOutput = false; // 直接串流,不佔記憶體
const int BufferSize = 16 * 1024;
byte[] buffer = new byte[BufferSize];
int read;
while ((read = stream.Read(buffer, 0, BufferSize)) > 0)
ctx.Response.OutputStream.Write(buffer, 0, read);
}
private PhotoSize ParseSize(string key) => key switch { "S" => PhotoSize.Small, "M" => PhotoSize.Medium, "L" => PhotoSize.Large, _ => PhotoSize.Original };
}
// 使用方式:<img src="PhotoHandler.ashx?PhotoID=123&Size=M" width="200" />
public class JsConfigHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.ContentType = "application/javascript; charset=utf-8";
string callback = ctx.Request.QueryString["callback"]; // JSONP 支援
var config = new { ApiBase = "/api/v1", Version = "1.2.3", Debug = false };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(config);
string output = string.IsNullOrEmpty(callback) ? json : $"{callback}({json})";
ctx.Response.Write(output);
}
}
// 頁面引用:<script src="JsConfigHandler.ashx?callback=initConfig"></script>
public class DynamicCssHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext ctx)
{
string theme = ctx.Request.QueryString["theme"] ?? "light";
ctx.Response.ContentType = "text/css; charset=utf-8";
ctx.Response.Cache.SetCacheability(HttpCacheability.Public);
ctx.Response.Cache.SetMaxAge(TimeSpan.FromHours(1));
string css = theme == "dark" ? GetDarkCss() : GetLightCss();
ctx.Response.Write(css);
}
private string GetDarkCss() => @":root{--bg:#1e1e1e;--fg:#ddd;--accent:#bb86fc;}";
private string GetLightCss() => @":root{--bg:#fff;--fg:#333;--accent:#6200ee;}";
}
// 頁面引用:<link href="DynamicCssHandler.ashx?theme=dark" rel="stylesheet" />
public class SitemapHandler : IHttpHandler
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.ContentType = "application/xml; charset=utf-8";
ctx.Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
ctx.Response.Write("<urlset xmlns=\"https://www.sitemaps.org/schemas/sitemap/0.9\">");
foreach (var url in SiteMapProvider.GetUrls())
{
ctx.Response.Write($"<url><loc>{HttpUtility.HtmlEncode(url)}</loc><changefreq>daily</changefreq></url>");
}
ctx.Response.Write("</urlset>");
}
}
public class LegacyScriptHandler : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.ContentType = "text/javascript; charset=utf-8";
ctx.Response.Write("document.write('<div class=\"banner\">歡迎光臨</div>');");
}
}
// 頁面引用:<script src="LegacyScriptHandler.ashx"></script>
IRequiresSessionState,IsReusable = false。IReadOnlySessionState,可設 IsReusable = true (無寫入鎖定)。public class DownloadHandler : IHttpHandler, IReadOnlySessionState
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext ctx)
{
string userId = ctx.Session["UserId"]?.ToString();
if (string.IsNullOrEmpty(userId)) { ctx.Response.StatusCode = 401; return; }
// 記錄下載日誌...
ctx.Response.Write(userId);
}
}
try { /* 核心邏輯 */ }
catch (FileNotFoundException) { ctx.Response.StatusCode = 404; ctx.Response.End(); }
catch (UnauthorizedAccessException) { ctx.Response.StatusCode = 403; ctx.Response.End(); }
catch (Exception ex) {
Log.Error(ex);
ctx.Response.StatusCode = 500;
ctx.Response.Write("Internal Error");
}
Response.BufferOutput = false:避免大檔案完全載入記憶體。Response.TransmitFile(path):直接由 IIS 透過 kernel-mode 傳送,CPU 佔用最低。Range 斷點續傳:需自行解析 Request.Headers["Range"] 並回應 206 Partial Content。/Handlers/),配合 web.config 限制僅允許 GET/POST。<customErrors mode="RemoteOnly" />。HtmlEncode/JavaScriptStringEncode 防 XSS。