Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

IIS 防止目錄檔案被下載:應用程式對應 + IHttpHandler 方案

編輯:關於伺服器

需求場景

保護特定目錄 (如 /encry/) 下所有檔案,防止直接 URL 存取下載,且不更改副檔名、不影響正常應用程式呼叫。

核心原理

  1. IIS 應用程式對應將所有副檔名 (或特定目錄) 導向 aspnet_isapi.dll,交由 ASP.NET 管線處理。
  2. 自訂 IHttpHandler 攔截請求,在 ProcessRequest 中實作權限檢查、讀取檔案串流輸出或拒絕存取。

實作步驟

1. IIS 新增萬用字元應用程式對應

  • IIS 管理員 → 網站屬性 → 主目錄 → 「配置」→ 「對應」頁籤 → 「新增」
  • 執行檔:C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll (依 .NET 版本調整)
  • 副檔名:.* (或留空啟用「驗證檔案是否存在」取消勾選)
  • 動詞:All verbs / GET,HEAD,POST,DEBUG

2. Web.config 註冊 HttpHandler

<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="encry/*.*" type="CustomHttpHandler.Class1, CustomHttpHandler" />
    </httpHandlers>
  </system.web>
</configuration>

path 可用萬用字元精確鎖定目錄;type 格式:「完整類別名, 組件名稱」。

3. 實作 IHttpHandler (Class1.cs)

using System;
using System.Web;

namespace CustomHttpHandler
{
    public class Class1 : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // 1. 自訂權限邏輯:檢查 Session、Cookie、IP、Referer 等
            // string referer = context.Request.ServerVariables["HTTP_REFERER"];

            // 2. 若驗證失敗
            context.Response.Write("您無權存取該資源");
            context.Response.StatusCode = 403;
            return;

            // 3. 驗證通過:讀取實體檔案並輸出
            // string physicalPath = context.Server.MapPath(context.Request.Path);
            // context.Response.ContentType = "application/octet-stream"; // 或依副檔名動態判斷
            // context.Response.TransmitFile(physicalPath);
        }

        public bool IsReusable { get { return false; } }
    }
}
  • 編譯為 CustomHttpHandler.dll 放入網站 /bin 目錄。
  • IsReusable = false 確保每請求新實例,避免狀態汙染。

優缺點與注意事項

優點缺點/風險
不改副檔名,對現有連結零影響所有攔截路徑請求經 ASP.NET 管線,靜態檔案效能較原生 IIS 略降
可實作任意複雜授權邏輯 (角色、時間、Referer、Token)需確保 aspnet_isapi.dll 版本與應用程式池 .NET 版本一致
支援斷點續傳、大檔案串流 (TransmitFile)若處理不當可能導致所有靜態資源 (CSS/JS/圖片) 亦被攔截而無法載入

最佳化建議

  • 精確限定 path:僅針對需保護目錄 (如 encry/*),避免全站攔截。
  • 靜態資源排除:若誤攔截靜態檔,可在 Handler 內依副檔名直接 TransmitFile 或放行。
  • IIS 7+ 整合模式:改在 <system.webServer><handlers> 註冊,並設定 preCondition="integratedMode"。
Copyright © Windows教程網 All Rights Reserved