Asp.net-Mvc
沒有控制器或動作名稱的 Asp.net mvc 路由
我正在嘗試將所有與現有控制器不匹配的 url 重定向到某個控制器。
例如,url mywebsite.com/newyork 應該被處理為 mywebsite.com/Cities/Info/newyork
我在我的 RegisterRoutes 中使用以下程式碼,但它似乎不起作用,因為我收到 404 響應:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Cities", url: "{cityname}", defaults: new { controller = "Cities", action = "Info", cityname= "" } );
您應該首先放置您的城市路線並刪除空的預設參數:
routes.MapRoute( name: "Cities", url: "{cityname}", defaults: new { controller = "Cities", action = "Info" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );路由按順序處理,因此您應該從最具體到最不具體(您的預設路由)。
由於您的 website.com/newyork 與預設路線匹配,因此它不會繼續您的城市路線。