In this blog, I will demonstrate how to version web api service using accept header in http request.
Create Web Application project with Web API Template:
For versioning, I find SDammann.WebApi.Versioning library really useful
With versioning library installed, create new class to get api version from accept-header. AcceptHeaderVersionedControllerSelector in SDammann.WebApi.Versioning.dll accepts only application/json. You extend AcceptHeaderVersionedControllerSelectorBase from that library to add custom logic for accept header manipulation.
In class above I am setting version = “1” if request does not contain any versioning information in accept-Header.
Update global.ascx.cs or WebApiConfig.cs to use this ControllerSelector instead of default one.
Change the namespace of the default ValuesController to use “Version1” in namespace.
Add another ValuesController under Version2 namespace:
All Set for testing:
Easy and powerful. AcceptHeaderVersionControllerSelector can be customized in lot of different ways to accommodate company policy for versioning.
I have been following Web API features for about a year now and I must say they are evolving very fast (May be because MS decided to make it open source).
In the latest RC version of Web API (2.1) they have made it even more easier to implement versioning than Web API 2.
Here is the overview of new features:
You can get the sample code which demonstrates versioning from here:
This is from the sample code which shows how to use IHttpRouteConstraint and RouteProviderAttribute for versioning
What is not quite evident from sample code is how powerful [VersionedRoute] attribute could be. You can apply is to Controller class itself like:
But even more interesting you can apply to individual routes within same controller as well
Personally, I found it little tricky to use it on controller and stick with IHttpControllerSelector if I have to do versioning based on controller class.
Here is a great source for this:
But [VersionedRoute] could really be useful if you need to do versioning only for certain routes in your application.
Happy versioning and hopefully this will help in versioning with Web API 2.1