20

我定义了以下路线:

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 并且 Route Debugger 没有出现在页面底部 - 我希望它会告诉我哪些位被映射,但是我什么都得不到。所有的观点都存在。

所以我假设我在路线定义上犯了一个错误 - 任何人都可以对此有所了解吗?另外,如何让 Route Debugger 向我展示 URL 如何映射到返回 404 的那些页面的路由字典中?

4

1 回答 1

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参数中只有两个参数。

所以需要从具体到一般。通常,如果您在两个路由定义中具有相同数量的参数,则添加的第一个路由将是选择的那个。

于 2011-05-07T00:42:31.423 回答