ASP.NET MVC 專案中設定路由將 https://www.test.com/reports/ 導向 https://www.test.com/ReaResport/List,但直接存取 /reports/ 卻回傳 403 - 禁止存取:存取被拒絕。
IIS 預設將 /reports/ 識別為實體目錄而非 MVC 路由。當網站根目錄下存在同名 reports 資料夾時,IIS 靜態檔案處理模組優先攔截請求,嘗試列出目錄內容,因預設禁止目錄瀏覽而回傳 403。
| 規則名稱 | 匹配模式 | 動作類型 | 用途 |
|---|---|---|---|
| ReportsRoute | ^reports/?$ | Redirect (302) | 處理 /reports 與 /reports/ 根路徑導向 |
| ReportsSubPath | ^reports/(.*) | Rewrite | 處理 /reports/子路徑 透明轉發 |
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| URL Rewrite | 不修改程式碼、效能好、支援正則 | 需安裝 IIS 模組 | 生產環境、既有專案快速修復 |
| RouteConfig 設定 | 純程式碼控制、版本管理友善 | 需處理實體目錄衝突 | 新專案、無同名目錄 |
| 重命名資料夾 | 最簡單 | 可能影響其他參考 | 資料夾無其他用途 |
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// 明確忽略 reports 實體目錄,交由 URL Rewrite 處理
routes.IgnoreRoute("reports/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
/reports/ → 302 導向 /ReaResport/List/reports/detail/123 → 透明轉發至 /ReaResport/detail/123