Skip to content

API Version Conventions

Chris Martinez edited this page Sep 14, 2016 · 10 revisions

API version conventions allow you to specify API version information for your services without having to use .NET attributes. There are a number of reasons why you might choose this option. The most common reasons are:

  • Centralized management and application of all service API versions
  • Apply API versions to services defined by controllers in external .NET assemblies
  • Dynamically apply API versions from external sources; for example, from configuration

Consider the following controller:

ASP.NET Web API

[RoutePrefix( "my" )]
public class MyController : ApiController
{
    [Route]
    public IHttpActionResult Get() => Ok();
}

ASP.NET Core

[Route( "my" )]
public class MyController : Controller
{
    [HttpGet]
    public IActionResult Get() => Ok();
}

Instead of applying the ApiVersionAttribute to the controller, we can instead choose to define a convention in the API versioning options.

ASP.NET Web API

configuration.AddApiVersioning( options =>
{
    options.Conventions.Controller<MyController>().HasApiVersion( 1, 0 );
} );

ASP.NET Core

services.AddApiVersioning( options =>
{
    options.Conventions.Controller<MyController>().HasApiVersion( 1, 0 );
} );

All of the semantics that can be expressed with .NET attributes can be defined using conventions. Consider what version 2.0 of the previous controller with interleaved API versions might look like:

ASP.NET Web API

[RoutePrefix( "my" )]
public class MyController : ApiController
{
    [Route]
    public IHttpActionResult Get() => Ok();

    [Route]
    public IHttpActionResult GetV2() => Ok();

    [Route( "{id:int}" )]
    public IHttpActionResult GetV2( int id ) => Ok();
}

ASP.NET Core

[Route( "my" )]
public class MyController : Controller
{
    [HttpGet]
    public IActionResult Get() => Ok();

    [HttpGet]
    public IActionResult GetV2() => Ok();

    [HttpGet( "{id:int}" )]
    public IActionResult GetV2( int id ) => Ok();
}

The API version conventions might then be defined as:

options.Conventions.Controller<MyController>()
                   .HasDeprecatedApiVersion( 1, 0 )
                   .HasApiVersion( 2, 0 )
                   .Action( c => c.GetV2() ).MapToApiVersion( 2, 0 )
                   .Action( c => c.GetV2( default( int ) ) ).MapToApiVersion( 2, 0 );
Clone this wiki locally