Skip to content

Versioning via the Query String

Chris Martinez edited this page Jul 28, 2016 · 5 revisions

The initial version of a controller may not have any API version attribution and will implicitly become the configured default API version. The default configuration uses the value 1.0.

ASP.NET Web API

[RoutePrefix( "api/helloworld" )]
public class HelloWorldController : ApiController
{
    [Route]
    public string Get() => "Hello world!";
}

ASP.NET Web API and OData v4.0

[ODataRoutePrefix( "People" )]
public class PeopleController : ODataController
{
    [ODataRoute]
    public IHttpActionResult Get( ODataQueryOptions<Person> options ) =>
        Ok( new[]{ new Person() } );
}

ASP.NET Core

[Route( "api/helloworld" )]
public class HelloWorldController : Controller
{
    [HttpGet]
    public string Get() => "Hello world!";
}

To create the next version of the controller, you can choose to create a new controller with the same route, but decorated it as API version 2.0. For example:

ASP.NET Web API

[ApiVersion( "2.0" )]
[RoutePrefix( "api/helloworld" )]
public class HelloWorldController : ApiController
{
    [Route]
    public string Get() => "Hello world!";
}

ASP.NET Web API and OData v4.0

[ApiVersion( "2.0" )]
[ControllerName( "People" )]
[ODataRoutePrefix( "People" )]
public class People2Controller : ODataController
{
    [ODataRoute]
    public IHttpActionResult Get( ODataQueryOptions<Person> options ) =>
        Ok( new[]{ new Person() } );
}

ASP.NET Core

[ApiVersion( "2.0" )]
[Route( "api/helloworld" )]
public class HelloWorld2Controller : Controller
{
    [HttpGet]
    public string Get() => "Hello world!";
}

The effect of this attribution is that the following requests match different controller implementations:

Request URL Matched Controller
/api/helloworld?api-version=1.0 HelloWorldController
/api/helloworld?api-version=2.0 HelloWorld2Controller
/api/People?api-version=1.0 PeopleController
/api/People?api-version=2.0 People2Controller

It’s important to note that only an undecorated controller will be inferred as the configured, default API version. Once a controller has any API version attribution, it will never be considered as the default API version again unless the API version attribute includes the default API version. This allows you permanently remove API versions over time.

Clone this wiki locally