Monday, December 15, 2008

Making ASP .NET MVC URIs RESTful

Out of the box the ASP .NET MVC implementation is nice, easy, and elegant. From what I understand they used a few patterns from, the RoR world. One thing that is not part of the default implementation is RESTful routing.

Thanks to the guys who are infinitely smarter than me that did MVCContrib, adding RESTful behavior (using SimplyRestfulRouteHandler) to a .NET MVC app is pretty simple.

  1. Download the MVCContrib libraries (I downloaded the source because I like to break stuff)
  2. Open up your ASP .NET MVC application and add a reference to the MVCContrib.dll
  3. Open up the Global.asax.cs and add the following line inside the ResgisterRoutes method: MvcContrib.SimplyRestful.SimplyRestfulRouteHandler.BuildRoutes(routes);
This is what you get:


ActionURLHttpForm
Show[controller]/[id]GET
Create[controller]POST
Update[controller]/[id]PUT
Update[controller]/[id]POSTPUT
Destroy[controller]/[id]DELETE
Destroy[controller]/[id]POSTDELETE
Index[controller]GET
New[controller]/newGET
Edit[controller]/[id]/editGET
Delete[controller]/[id]/deleteGET
So if we we're dealing with people, for instance, the URI and verb maps might look like:

HTTP verb: [GET] (for show)
URI: https://api.mydomain.com/v1/People/1234

HTTP verb: [PUT] (for update)
URI: https://api.mydomain.com/v1/People/1234

HTTP verb: [POST] (for create)
URI: https://api.mydomain.com/v1/People/


so on...

So what if you wanted to address hierarchy with the object using the same URI scheme? Let's say you wanted to get all of the addresses for a particular person and addresses were a child of person:

HTTP verb: [GET]
URI: https://api.mydomain.com/v1/People/1234/addresses



Thanks to the slick implementation of the RouteHandler all you have to do is add another call to BuildRoutes using an overload that accepts an "areaPrefix"

SimplyRestfulRouteHandler.BuildRoutes(routes, "People/{individualID}");

So now you can use:
https://api.mydomain.com/v1/People/1/addresses <-- collection
https://api.mydomain.com/v1/People/1/addresses/3 <-- single
https://api.mydomain.com/v1/addresses/3 <--single no context

No comments:

Post a Comment