Chris F Carroll
Chris F Carroll

Reputation: 12370

Routing for REST style urls

I wish to set up routing to allow the following:

/entity/id          //id is Guid
/entity/id          //id is int32
/entity/actionname  //actionname is string matching neither Guid nor Int

Simple, I thought, that's what RouteConstraints solve:

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

where, I believe, the order matters: the more-specific matches have to come before the entity/action route, which would otherwise match everything.

But this does not work.

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

results in

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

instead of

entity/00000000-0000-0000-0000-000000000000

How can I fix it?

(I'm on asp.net Core 1.1, although I believe the question is valid back to MVC4)

Upvotes: 4

Views: 79

Answers (1)

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

It will generate expected result if you pass action name "Index" , or pass null, as the first parameter.

Upvotes: 2

Related Questions