API Versioning in ASP.NET Web API 2.1

Thanks to new changes to Attribute Routing in ASP.NET Web API 2.1 there are two easy ways to version your RESTful API now. Let’s take a look at two approaches we can use for API versioning in Web API 2.1:

Approach 1
  1. Separate your controllers of different versions by file naming (e.g. MyV1Controller, MyV2Controller) or by namespaces (e.g. MyApi.V1.MyController and MyApi.V2.MyController)
  2. Use VersionedRoute atrribue for your controller:
    [VersionedRoute("api/my", 1)]
    public class MyV1Controller : ApiController { ... }
    [VersionedRoute("api/my", 2)]
    public class MyV2Controller : ApiController { ... }

    Now client should include the following header item in the request:
    api-version: 2

Approach 2

Another approach to have version number in the URI is to use RoutePrefix instead as follows:

public class MyV1Controller : ApiController { ... }
public class MyV2Controller : ApiController { ... }

It’s a little bit easier because there is no need to set API Version header but considered as a second class solution when talking about best practices ;-)

Dig more!


4 thoughts on “API Versioning in ASP.NET Web API 2.1

  1. Thanks for sharing, they really simplified versioning with version 2.1, doing this in version web API version 1 was not that simple. I’m fan if keeping URL static and version by sending headers and fall back to latest version if the header was not sent. What is your favourite way to version APIs?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>