我定义了以下路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(name: "Homepage", url: "", defaults: new { controller = "Restaurants", action = "Search" });
routes.MapRoute(name: "About", url: "about", defaults: new { controller = "Home", action = "About" });
routes.MapRoute(name: "Disclaimer", url: "disclaimer", defaults: new { controller = "Home", action = "Disclaimer" });
routes.MapRoute(name: "Contact", url: "contact", defaults: new { controller = "Home", action = "Contact" });
routes.MapRoute(name: "RestaurantDetails", url: "{id}/{slug}", defaults: new { controller = "Restaurant", action = "Details" });
routes.MapRoute(name: "RestaurantLocationDetails", url: "{id}/{restaurantSlug}/{locationSlug}", defaults: new { controller = "Restaurant", action = "LocationDetails" });
routes.MapRoute(name: "Api", url: "api/{action}", defaults: new { controller = "Api" });
}
我找到了一些给出404的路线,所以我安装了RouteDebugger NuGet包。
它显示了我对前4个路径的期望,但是在最后3个路由中我仍然得到404并且alas Route Debugger没有出现在页面底部 - 我希望它能告诉我哪些位得到了映射,但我一无所获。所有观点都存在。
所以我假设我在路线定义上犯了一个错误 - 任何人都可以对此有所了解吗?另外,如何让Route Debugger向我展示如何将URL映射到返回404的页面的路由字典?
答案 0 :(得分:22)
您需要更改路线的顺序。
routes.MapRoute(name: "Homepage", url: "", defaults: new { controller = "Restaurants", action = "Search" });
routes.MapRoute(name: "About", url: "about", defaults: new { controller = "Home", action = "About" });
routes.MapRoute(name: "Disclaimer", url: "disclaimer", defaults: new { controller = "Home", action = "Disclaimer" });
routes.MapRoute(name: "Contact", url: "contact", defaults: new { controller = "Home", action = "Contact" });
routes.MapRoute(name: "Api", url: "api/{action}", defaults: new { controller = "Api" });
routes.MapRoute(name: "RestaurantLocationDetails", url: "{id}/{restaurantSlug}/{locationSlug}", defaults: new { controller = "Restaurant", action = "LocationDetails" });
routes.MapRoute(name: "RestaurantDetails", url: "{id}/{slug}", defaults: new { controller = "Restaurant", action = "Details" });
路线按照添加到路线列表的顺序进行处理。
例如:api/action
也匹配RestaurantDetails
路由,因为路由url参数中只有两个参数。
所以它需要从具体到一般。通常,如果在两个路径定义中具有相同数量的参数,则添加的第一个路径将是所选择的路径。