ASP.NET MVC 路由無強制要求命名,但命名路由可解決 URL 產生時的歧義並提升效能。
註冊路由:
routes.MapRoute("Test", "code/p/{action}/{id}", new { controller="Section", action="Index", id=UrlParameter.Optional });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller="Home", action="Index", id=UrlParameter.Optional });
routes.MapPageRoute("new", "static/url", "~/aspx/SomePage.aspx"); // 放最前
使用 @Html.RouteLink 產生連結時,若不指定路由名稱,路由引擎依順序匹配,導致前兩個連結皆被 static/url 路由捕獲 (無參數),產生無效 URL /static/url?controller=...。
@Html.RouteLink(linkText: "route:test", routeName: "Test", routeValues: new { controller="Section", action="Index", id=123 })
@Html.RouteLink(linkText: "Default", routeName: "Default", routeValues: new { controller="Home", action="Index", id=123 })
明確指定 routeName 讓引擎直接定位路由,避免歧義、提升效能。命名路由如同人名,是命運的縮寫。