Asp.net MVC 5 MapRoute的多个路由

Sso*_*ncy 3 asp.net asp.net-mvc asp.net-mvc-routing maproute asp.net-mvc-5

我在RouteConfig中有3条路由:

routes.MapRoute(
    name: "ByGroupName",
    url: "catalog/{categoryname}/{groupname}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
    name: "ByCatName",
    url: "catalog/{categoryname}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
    name: "ByBrandId",
    url: "catalog/brand/{brandId}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
Run Code Online (Sandbox Code Playgroud)

这是我的动作控制器接收参数:

public ActionResult Catalog(
    string categoryName = null,
    string groupName = null,
    int pageNumber = 1,
    int orderBy = 5,
    int pageSize = 20,
    int brandId = 0,
    bool bundle = false,
    bool outlet = false,
    string query_r = null)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)

当我在视图中使用与的链接时@Url.RouteUrl("ByBrandId", new {brandId = 5}),我将参数“ categoryname” =“ brand”和brandId = 0而不是仅brandId = 5用作参数...

当我"http://localhost:3453/catalog/brand/5"使用“ ByBrandId” routeurl进行呼叫时,我想在actioncontroller中获取brandId = 5 ..."http://localhost:3453/catalog/Catalog?brandId=1"

谢谢

Nig*_*888 5

您的路由配置错误。如果传递URL /Catalog/brand/something,它将始终ByGroupName路由匹配,而不是预期的ByBrandId路由。

首先,您应该更正顺序。而且,除了可选的组名之外,前2条路由完全相同,因此您可以简化为:

routes.MapRoute(
    name: "ByBrandId",
    url: "catalog/brand/{brandId}",
    defaults: new { controller = "Catalog", action = "Catalog" }
);
routes.MapRoute(
    name: "ByGroupName",
    url: "catalog/{categoryname}/{groupname}",
    defaults: new { controller = "Catalog", action = "Catalog", groupname = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

现在,当您使用@Url.RouteUrl("ByBrandId", new {brandId = 5})它时,应该会给您预期的输出/catalog/brand/5

有关完整的说明,请参见asp.net mvc中的“ 为什么先在特殊路由之前映射特殊路由”