保護特定目錄 (如 /encry/) 下所有檔案,防止直接 URL 存取下載,且不更改副檔名、不影響正常應用程式呼叫。
aspnet_isapi.dll,交由 ASP.NET 管線處理。IHttpHandler 攔截請求,在 ProcessRequest 中實作權限檢查、讀取檔案串流輸出或拒絕存取。C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll (依 .NET 版本調整)<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="encry/*.*" type="CustomHttpHandler.Class1, CustomHttpHandler" />
</httpHandlers>
</system.web>
</configuration>
path 可用萬用字元精確鎖定目錄;type 格式:「完整類別名, 組件名稱」。
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/圖片) 亦被攔截而無法載入 |
encry/*),避免全站攔截。TransmitFile 或放行。<system.webServer><handlers> 註冊,並設定 preCondition="integratedMode"。