【发布时间】:2017-03-24 17:21:32
【问题描述】:
我希望设置路由以允许以下操作:
/entity/id //id is Guid
/entity/id //id is int32
/entity/actionname //actionname is string matching neither Guid nor Int
简单,我想,这就是 RouteConstraints 解决的问题:
routes.MapRoute(
name: "entity/id:guid",
template: "{controller}/{id:guid}",
defaults:new{action="Index"});
routes.MapRoute(
name: "entity/id:int",
template: "{controller}/{id:int}",
defaults: new { action = "Index" });
routes.MapRoute(
name: "entity/action",
template: "{controller=home}/{action=index}");
我认为顺序很重要:更具体的匹配必须在实体/动作路由之前,否则会匹配所有内容。
但这不起作用。
@Url.Action("", "entity", new { id = Guid.NewGuid() })
结果
entity?id=00000000-0000-0000-0000-000000000000
而不是
entity/00000000-0000-0000-0000-000000000000
我该如何解决?
(我使用的是 asp.net Core 1.1,尽管我相信这个问题在 MVC4 中是有效的)
【问题讨论】:
-
如果您提供参数“Index”而不是空字符串“”会怎样。会有什么不同吗?
-
我很确定这不是由于您的路线,而是由于
Url.Action的工作方式。 -
@AndriiLitvinov:嗯。很好。是的, Url.Action("Index", "entity", new { id = Guid.NewGuid() }) 给出了正确的结果,所以如果你想粘贴答案,你会得到分数。确定是bug?使用 "" 作为操作应该会导致使用默认操作
-
@sleeyuen 是的,这与 Url.Action 的工作方式有关,但它的工作方式必须由路由表驱动。不是吗?
标签: asp.net-mvc asp.net-core-mvc asp.net-mvc-routing