I installed the new ASP .Net MVC4 beta on my machine and have been trying to understand how the Web API works. I built a demo for a single collection (ex. books). I followed the example on the asp.net website. I implemented my own methods for posting to a collections i.e. adding a new book, getting all books, getting a particular book, updating a book and deleting a book record. All this works fine.
Ex:
POST /books - adds a new book
GET /books - gets all books
GET /books/1 - get a particular book
PUT /books/1 - update a particular book
DELETE /books/1 - delete a particular book
Now I want to add another collection inside the books collection, say authors and want to implement the same POST, PUT, GET and DELETE calls for the new collection
I want the new calls to be something like this:
POST /books/1/authors - add a new author to a book
GET /books/1/authors - gets all authors of a book
GET /books/1/authors/a@a.com - get a particular author for a book
PUT /books/1/authors/a@a.com - update a particular author for a book
DLETE /books/1/authors/a@a.com - delete a particular author for a book
I am confused how to add a route to make this call work. By default I get this route with the project.
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
What is the right way to handle routes in this pattern for collections and associations between them?
Managing routes in Global can be confusing and error prone. Personally, I found the Attribute Routing package helps simplify routing configuration greatly. This article explains how to acquire and use it.
http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/