Thursday, September 26, 2013

Web API Attribute Routing

ASP.Net Web API Attribute Routing is a new feature released with Web API 2. In this post I'll use the project which I developed in my previous post.
In the project uninstall nuget packages for ASP.Net web API. Now re-install RC release of Web API version 5.
In previous post I had to comment some methods in CarApiController and ModelApiConotroller.
Reason for that is both traditional and verb-based routing cannot be used in the same ApiController. But that issue is fixed with Web API 2.
First, in WebApiConfig class, map Http Attribute Routes like below.
Change code in CarApiController and ModelApiConotroller like below. As you can see, in HttpGetAttribute I have passed routing path for the action.
Now change code appropriately in Client project. If you browse by 'http://localhost:52414/api/ModelApi/43213BE0-F9CF-4266-9B04-6B4645BEF41E', this will call GetModel action.
But if you browse by 'http://localhost:52414/api/ModelApi/43213BE0-F9CF-4266-9B04-6B4645BEF41E/Make', this will call to GetModels action.
Using attribute routing we can have versioning of Web API and much more things.

You can find the source code of this in GitHub.

No comments:

Post a Comment