Asp.net MVC 5 MapRoute的多个路由 [英] Asp.net MVC 5 MapRoute for multiple routes
问题描述
我在RouteConfig中有3条路由:
I have 3 routes in RouteConfig:
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" }
);
这是我的动作控制器接收参数:
and this is my action controller receiving parameters:
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 ...
when I Use in view a link with @Url.RouteUrl("ByBrandId", new {brandId = 5})
, I get in Action a parameter "categoryname"="brand" and brandId=0 instead of only brandId=5...
当我使用"ByBrandId" routeurl调用"http://localhost:3453/catalog/brand/5"
时,我想在actioncontroller中获取brandId = 5,相当于"http://localhost:3453/catalog/Catalog?brandId = 1"
When I Call "http://localhost:3453/catalog/brand/5"
with "ByBrandId" routeurl I want to get brandId=5 in actioncontroller..., the equivalent of "http://localhost:3453/catalog/Catalog?brandId=1"
谢谢
推荐答案
您的路由配置不正确.如果您传递URL /Catalog/brand/something
,它将始终匹配 ByGroupName
路由,而不是预期的 ByBrandId
路线.
Your routing is misconfigured. If you pass the URL /Catalog/brand/something
it will always match the ByGroupName
route instead of the intended ByBrandId
route.
首先,您应该更正顺序.而且,除了可选的组名之外,前2条路由完全相同,因此您可以简化为:
First of all, you should correct the order. But also, the first 2 routes are exactly the same except for the optional group name, so you can simplify to:
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",新的{brandId = 5})
时,它应该会为您提供预期的输出/catalog/brand/5
Now when you use @Url.RouteUrl("ByBrandId", new {brandId = 5})
it should give you the expected output /catalog/brand/5
.
有关完整说明,请参见为什么先在asp.net mvc中将特殊路由映射到普通路由之前.
See Why map special routes first before common routes in asp.net mvc for a complete explanation.
这篇关于Asp.net MVC 5 MapRoute的多个路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!