Asp.net MVC 5多路由的MapRoute

3

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

以下是我的Action Controller接收参数的示例:

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

当我在视图中使用@Url.RouteUrl("ByBrandId", new {brandId = 5})链接时,在操作中我得到一个参数"categoryname"="brand"和brandId=0,而不是仅有的brandId=5...
当我调用带有"ByBrandId"路由的"http://localhost:3453/catalog/brand/5"时,我希望在操作控制器中得到brandId=5,这相当于"http://localhost:3453/catalog/Catalog?brandId=1" 谢谢。
1个回答

6

您的路由配置有误。如果您使用URL /Catalog/brand/something,它将总是匹配ByGroupName路由,而不是预期的ByBrandId路由。

首先,您应该更正顺序。但是,前两个路由除了可选组名之外完全相同,因此您可以简化为:

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
请参考为什么在asp.net mvc中先映射特殊路由再映射常规路由获取完整解释。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接