I want to build a RESTful Json Api for my MVC3 application. I need help with handling multiple Http Verbs for the manipulation of a single object instance.
What I've read/studied/tried
MVC attributes (HttpGet
, HttpPost
, etc.) allow me to have a controller with multiple actions sharing the same name, but they still must have different method signatures.
Route constraints happen in the routing module before MVC kicks in and would result in me having 4 explicit routes, and still require individually named controller actions.
ASP.NET MVC AcceptVerbs and registering routes
Building a custom Http Verb Attribute could be used to snatch the verb used to access the action and then pass it as an argument as the action is invoked - the code would then handle switch cases. The issue with this approach is some methods will require authorization which should be handled at the action filter level, not inside the action itself.
http://iwantmymvc.com/rest-service-mvc3
Requirements / Goals
One route signature for a single instance object, MVC is expected to handle the four main Http Verbs: GET, POST, PUT, DELETE.
context.MapRoute("Api-SingleItem", "items/{id}", new { controller = "Items", action = "Index", id = UrlParameter.Optional } );
When the URI is not passed an Id parameter, an action must handle
POST
andPUT
.public JsonResult Index(Item item) { return new JsonResult(); }
When an Id parameter is passed to the URI, a single action should handle
GET
andDELETE
.public JsonResult Index(int id) { return new JsonResult(); }
Question
How can I have more than one action (sharing the same name and method signature) each respond to a unique http verb. Desired example:
[HttpGet]
public JsonResult Index(int id) { /* _repo.GetItem(id); */}
[HttpDelete]
public JsonResult Index(int id) { /* _repo.DeleteItem(id); */ }
[HttpPost]
public JsonResult Index(Item item) { /* _repo.addItem(id); */}
[HttpPut]
public JsonResult Index(Item item) { /* _repo.updateItem(id); */ }