萬盛學電腦網

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

ASHX 處理常式進階應用:輸出圖片、JS、CSS、XML 與 Session 存取完整範例

前言

.ashx 不僅能輸出純文字,透過設定 Content-Type 可偽裝成圖片、JavaScript、CSS、XML 等任何 MIME 類型,實現動態資源輸出。本文彙整五大實戰模式,並解決 Session 存取、快取控制、錯誤處理等關鍵細節。

一、模式 1:動態圖片輸出 (含尺寸參數)

<%@ 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" />

二、模式 2:輸出 JavaScript (支援 JSONP / 模組載入)

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>

三、模式 3:動態 CSS 輸出 (主題切換)

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" />

四、模式 4:XML 輸出 (Sitemap / RSS / API)

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>");
    }
}

五、模式 5:內嵌 Script 文件輸出 (document.write 時代遺留)

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>

六、關鍵進階主題

1. Session 存取

  • 讀寫:實作 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);
    }
}

2. 錯誤處理與 HTTP 狀態碼

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");
}

3. 大檔案傳輸最佳化

  • Response.BufferOutput = false:避免大檔案完全載入記憶體。
  • Response.TransmitFile(path):直接由 IIS 透過 kernel-mode 傳送,CPU 佔用最低。
  • 支援 Range 斷點續傳:需自行解析 Request.Headers["Range"] 並回應 206 Partial Content。

七、部署與安全提醒

  • 將 .ashx 放在獨立資料夾 (如 /Handlers/),配合 web.config 限制僅允許 GET/POST。
  • 生產環境關閉詳細錯誤:<customErrors mode="RemoteOnly" />。
  • 輸出使用者輸入內容時務必 HtmlEncode/JavaScriptStringEncode 防 XSS。
copyright © 萬盛學電腦網 all rights reserved