1

I need to сlarify. I have .net mvc app and I use Microsoft/aspnet-api-versioning (for ASP.NET Core). And I have 2 controllers:

[ApiVersion("1.0")]
[Route("[controller]")]
public class OneController : Controller
{

    [HttpGet]
    public string Get()
    {
       return "Hello. I'm OneController";
    }
}

and

[ApiVersion("1.1")]
[Route("[controller]")]
public class TwoController : Controller
{

    [HttpGet]

    public string Get()
    {
        return "Hello. I'm TwoController";
    }
}

TwoController I added after release API with OneController. And now if I try to use "http://localhost:59719/One?api-version=1.1" i see error:

The HTTP resource that matches the request URI 'http://localhost:59719/test?api-version=1.1' does not support the API version '1.1'.

Should I use different versions for different controllers or there is way to use one (latest) version for any request?

I understand I can add [ApiVersion("1.1")] to ALL controllers, but if I have 20 controllers...

Thanks for help.

Puzirki
  • 442
  • 5
  • 16

2 Answers2

4

You can define a default api version using the ApiVersioningOptions class and use this default version if none is specified:

`services.AddApiVersioning(o =>
{
    o.AssumeDefaultVersionWhenUnspecified = true;
    o.DefaultApiVersion = new ApiVersion(1 , 0);
});`

Besides, you should take a look at this excellent post on API versioning in ASP.NET from Scott Hanselman: https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

arnaudauroux
  • 740
  • 6
  • 10
0

In your example above, you have two different controllers with two different API versions. There is no direct relationship between these two. If you're trying to apply API versions in a centralized manner, you can achieve this using the Conventions API. You can even author and apply your own conventions via the IControllerConvention interface.

// same result as the attributes above
options.Conventions.Controller<OneController>().HasVersion(1,0);
options.Conventions.Controller<TwoController>().HasVersion(1,1);

// can also be achieved using only controller types
options.Conventions.Controller(typeof(OneController)).HasVersion(1,0);
options.Conventions.Controller(typeof(TwoController)).HasVersion(1,1);


// register your own convention that applies API versions to all controllers
options.Conventions.Add(new MyCustomApiVersionConvention());

You can also use an approach similar to what @arnaudauroux suggested, which would be:

services.AddApiVersioning(options =>
{
  options.AssumeDefaultVersionWhenUnspecified = true;
  options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
});

Now any request without an API version will select the current (or highest) API version available. Beware that this could break clients.

Chris Martinez
  • 3,185
  • 12
  • 28