實作 `IHttpHandler` 攔截 `.jpg` 請求,檢查 `Request.UrlReferrer.Host` 是否為允許域名,非法請求回傳預設圖片 (`no.jpg`),合法請求輸出原圖。在 `web.config` 註冊 `
using System.Web;
public class JpgHandler : IHttpHandler {
public bool IsReusable => true;
public void ProcessRequest(HttpContext context) {
string physicalPath = context.Server.MapPath(context.Request.FilePath);
string referrerHost = context.Request.UrlReferrer?.Host?.ToLower();
// 無 Referrer 或非本域 → 回傳預設圖
if (string.IsNullOrEmpty(referrerHost) || !referrerHost.Contains("mydomain.com")) {
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(context.Server.MapPath("~/no.jpg"));
return;
}
// 合法請求:輸出原圖
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(physicalPath);
}
}
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.jpg" type="JpgHandler, MyAssembly" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="JpgAntiLeech" verb="*" path="*.jpg"
type="JpgHandler, MyAssembly" preCondition="integratedMode" />
</handlers>
</system.webServer>
</configuration>
| 方案 | 優點 | 缺點 |
|---|---|---|
| HttpHandler (本文) | 邏輯集中、支援動態判斷 | 所有圖片經管線、Referrer 可偽造 |
| URL Rewrite (IIS/ARR) | 效能高、原生模組 | 規則複雜、動態邏輯難寫 |
| 簽名 URL (Token) | 安全性高、可設過期時間 | 需改造所有圖片連結生成邏輯 |
| CDN 防盜連 (Referer 白名單) | 邊緣攔截、零代碼 | 同樣依賴 Referrer |