3

We am using aspnet-api-version for version our API's. While the library allows interleaving multiple version implementation on one controller.

[ApiVersion( "2.0" )]
[ApiVersion( "3.0" )]
[RoutePrefix( "api/helloworld" )]
public class HelloWorld2Controller : ApiController
{
    [Route]
    public string Get() => "Hello world v2.0!";

    [Route, MapToApiVersion( "3.0" )]
    public string GetV3() => "Hello world v3.0!";
}

We want to keep version specific controller separate.

The problem I see with version specific controller and using this library is that we have to re implement all the API methods again irrespective of whether they have changed or not. Consider this example

[RoutePrefix("api/v{version:apiVersion}/values")]
[ApiVersion( "1.0" )]
public class ValuesController : ApiController
{
    // GET api/values
    [Route]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [Route("{id:int}")]
    [Route, MapToApiVersion( "1.0" )]
    public string Get(int id)
    {
        return id.ToString();
    }
}


[RoutePrefix("api/v{version:apiVersion}/values")]
[ApiVersion( "2.0" )]
public class ValuesControllerV2 : ValuesController
{
    // GET api/values/5
    [Route("{id:int}")]
    [Route, MapToApiVersion( "2.0" )]
    public string Get(int id)
    {
        return id.ToString();
    }
}

V1 api (using ValuesController) defines two API function Get and Get(ById). But v2 api ValuesControllerV2 while overrides Get(ById), it has to re-implement or call into the base method for Get to make the Get API available on V2.

Is there a better strategy where we do not have to re-implement or write pass through for all functions that remain same on API upgrades.

Chandermani
  • 42,589
  • 12
  • 85
  • 88

1 Answers1

3

First, I would recommend assessing what your versioning policy will be. Most service authors (and/or companies) define a policy like N-2. This will help you determine how big this issue is or whether it's even an issue at all.

You can use inheritance, but there be dragons. In Web API, you have additional things to do in order to make it work. The built-in implementation does not honor inherited RoutePrefixAttribute or RouteAttribute. You should also consider that you cannot uninherit an action. This makes the strategy very messy if you sunset an API. Not all versioning scenarios are backward compatible or roll-forward.

I strongly recommend you keep your business logic outside of the service. Common base class non-action methods or extension methods can help reduce duplicate code. If the implementation of each action is small and you have an established versioning policy, then duplication is less of an issue.

Either method or a combination of both should provide plenty of flexibility.

Chris Martinez
  • 3,185
  • 12
  • 28