首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 結合 HttpHandler 實現圖片防盜連

     編輯:ASP.NET 基礎

實作 `IHttpHandler` 攔截 `.jpg` 請求,檢查 `Request.UrlReferrer.Host` 是否為允許域名,非法請求回傳預設圖片 (`no.jpg`),合法請求輸出原圖。在 `web.config` 註冊 `` 映射 `*.jpg`。

Handler 完整程式碼

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

web.config 註冊

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

關鍵細節與增強

  • Referrer 可偽造:此法僅阻擋一般熱連,無法防技術型盜連。生產環境建議結合簽名 URL (帶時間戳+HMAC) 或Token 驗證。
  • 靜態檔案處理:IIS 7+ 整合模式下,`*.jpg` 預設由 `StaticFileModule` 處理,需確保 Handler 排序優先或設 `runAllManagedModulesForAllRequests="true"`。
  • 快取頭:輸出圖片時加上 `context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetMaxAge(TimeSpan.FromDays(30));` 利用瀏覽器快取減少頻寬。
  • 支援多副檔名:`path="*.jpg,*.png,*.gif"` 或分別註冊多行。
  • 排除特定目錄:在 Handler 內判斷 `context.Request.Path.StartsWith("/public/")` 直接放行。

替代方案比較

方案優點缺點
HttpHandler (本文)邏輯集中、支援動態判斷所有圖片經管線、Referrer 可偽造
URL Rewrite (IIS/ARR)效能高、原生模組規則複雜、動態邏輯難寫
簽名 URL (Token)安全性高、可設過期時間需改造所有圖片連結生成邏輯
CDN 防盜連 (Referer 白名單)邊緣攔截、零代碼同樣依賴 Referrer
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved