Versioning in WebApi with Accept-Header

Standard

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:

start

For versioning, I find SDammann.WebApi.Versioning library really useful

http://www.nuget.org/packages/SDammann.WebApi.Versioning/

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.

acceptHeaderClas

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.

Config

Change the namespace of the default ValuesController to use “Version1” in namespace.

V1Values

Add another ValuesController under Version2 namespace:

V2Values

All Set for testing:

v1TestV2Test

Easy and powerful. AcceptHeaderVersionControllerSelector can be customized in lot of different ways to accommodate company policy for versioning.

Happy versioning!!!

Versioning with Web API 2.1

Standard

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:

http://blogs.msdn.com/b/webdev/archive/2013/12/09/asp-net-and-web-tools-2013-2-preview-for-visual-studio-2013.aspx

You can get the sample code which demonstrates versioning from here:

https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/RoutingConstraintsSample/ReadMe.txt

This is from the sample code which shows how to use IHttpRouteConstraint and RouteProviderAttribute for versioning

VersionedRoute:

VersionedRoute

IHttpRouteConstraint :

VersionConstraint

What is not quite evident from sample code is how powerful [VersionedRoute] attribute could be. You can apply is to Controller class itself like:

VersionedController

But even more interesting you can apply to individual routes within same controller as well

VersionedRouteIndividual

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.

IHttpControllerSelector

Here is a great source for this:

Nuget Versioning

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