bluedot
bluedot

Reputation: 782

Is it possible to use API versioning for specific methods within a controller in ASP.NET Core?

I'm using the API versioning methods provided by Microsoft.AspNetCore.Mvc.Versioning (v4.1). So in the startup class I have the following:

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers();

  services.AddMvc(options => options.Filters.Add<ExceptionFilter>());

  services.AddApiVersioning(options =>
  {
      options.ApiVersionReader = new MyCustomVersionReader(configuration);
      options.AssumeDefaultVersionWhenUnspecified = false;
      options.ReportApiVersions = true;
      options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
  });            
}

In the controller I can then add annotation [ApiVersion("1.0")] to the controller or individual methods.

[HttpGet]
[ApiVersion("1.0")]
public async Task<IActionResult> Get() {...}

Using this, all calls to the api have to have version info in the request header.

However, is it possible to have a specific method within the controller not require a version?

e.g.

[HttpGet]
[ApiVersion("1.0")]
public async Task<IActionResult> Method1() {...} //requires version in header

[HttpGet]
public async Task<IActionResult> Method2() {...} //does not require version in header

When I try the above (omitting the ApiVersion annotation for Method2) I still get the following error:

'An API version is required, but was not specified.'

Thank you for helping!

Upvotes: 2

Views: 2391

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

I think you can use [ApiVersionNeutral] attribute.You can see my demo below.

First in your startup add:

 options.Conventions.Controller<HomeV1Controller>().HasApiVersion(new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0));

Then in your HomeV1Controller:

[Route("api/[controller]")]
[ApiController]
public class HomeV1Controller : ControllerBase
{
    [HttpGet("get")]
    public string Get() => "Ok1";

    [HttpGet("getv2")]
    [ApiVersionNeutral]
    public string GetV2() => "Ok2";
}

Test result: enter image description here

Upvotes: 3

Related Questions