路由是 MVC 應用的「導航儀」,將外部 URL 映射為內部 Controller/Action。本文系統梳理路由表配置、預設路由規則、參數預設值、以及常見映射案例。
UrlRoutingModule 至 system.web.httpModules、system.webServer.modules 等區段——勿刪除,否則路由失效。Application_Start 中建立路由表,核心代碼:public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 排除 WebResource.axd 等
routes.MapRoute(
"Default", // 路由名稱
"{controller}/{action}/{id}", // URL 模板
new { controller="Home", action="Index", id=UrlParameter.Optional } // 預設值
);
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
URL 遵循 /{controller}/{action}/{id} 三段式:
所有參數皆可選,預設值:Home/Index/空字串。
| 請求 URL | Controller | Action | id | 執行代碼 |
|---|---|---|---|---|
| /Home/Index/3 | Home | Index | 3 | HomeController.Index(3) |
| /Home/Index | Home | Index | (空) | HomeController.Index() |
| /Home | Home | Index | (空) | HomeController.Index() |
| / | Home | Index | (空) | HomeController.Index() |
AreaRegistration.RegisterAllAreas() 支援大型專案模組化,每個 Area 擁有獨立路由表。
使用正則限制參數格式:routes.MapRoute(..., new { id = @"\d+" }) 確保 id 為純數字。
@Url.RouteUrl("Product", new { productId = 123 }) 生成 /Product/123,避免硬編碼 URL。
IgnoreRoute 排除傳統 .asmx、.ashx、靜態資源,防止被 MVC 攔截。