Travis Parks
Travis Parks

Reputation: 8695

MVC Routes With Embedded IDs

We want to have a route that looks like this:

/account/123/dosomething/234

In this case, account would be the controller and requesttrafficid would be the action, I guess. I am assuming I can define this route like this:

{controller}/{accountId}/{action}/{id}

In this case, the two IDs just become parameters of the action.

The question is: can do something like this for Web API?

Our normal MVC controllers are just returning views and other static content. All of our data comes from the API. We want our routes to be as close as possible, something like this:

api/account/123/dosomething/234

Based on my understanding, account wouldn't be the API controller, it would be dosomething. The two IDs just become parameters again. But how do I define this route? Do I just hard-code the 'account' part?

Upvotes: 0

Views: 60

Answers (2)

Travis Parks
Travis Parks

Reputation: 8695

With AttributeRouting, this is a piece of cake: http://attributerouting.net. You just put the placeholders at the right spot in your URL and MVC handles the rest.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239470

If you're only concern is being able to make the action portion of the route the same, you have two choices:

  1. You're not required to use the naming convention of [Method]Action. If you don't follow this convention, you just need to specify which method applies with the appropriate attribute:

    // These are functionally equivalent:
    
    public JsonResult GetSomething(int id) { ... }
    
    [HttpGet]
    public JsonResult DoSomething(int id) { ... }
    
  2. If you want to follow convention, but you want to customize the action name for routing purposes, you can use the ActionName attribute:

    [ActionName("dosomething")]
    public JsonResult GetSomething(int id) { ... }
    

Upvotes: 1

Related Questions