Asp.net 多路由的 MVC 5 MapRoute

Asp.net MVC 5 MapRoute for multiple routes

我在 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" }
);

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

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)
{
// ...
}

当我在视图中使用 link 和 @Url.RouteUrl("ByBrandId", new {brandId = 5}) 时,我在 Action 中得到一个参数 "categoryname"="brand" 和 brandId=0,而不仅仅是 brandId=5 ...

当我使用 "ByBrandId" routeurl 调用 "http://localhost:3453/catalog/brand/5" 时,我想在 actioncontroller 中获取 brandId=5...,相当于 "http://localhost:3453/catalog/Catalog?brandId=1"

谢谢

您的路由配置错误。如果您传递 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 }
);

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

有关完整说明,请参阅