REST 样式 url 的路由

Routing for REST style urls

我希望设置路由以允许以下操作:

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

我认为顺序很重要:更具体的匹配项必须出现在 entity/action 路由之前,否则它将匹配所有内容。

但这不起作用。

@Url.Action("", "entity", new { id = Guid.NewGuid() })

结果

entity?id=00000000-0000-0000-0000-000000000000

而不是

entity/00000000-0000-0000-0000-000000000000

我该如何解决?

(我在 asp.net 核心 1.1,虽然我相信这个问题在 MVC4 之前是有效的)

如果您传递操作名称 "Index" 或传递 null 作为第一个参数,它将生成预期结果。