Search code examples
apiasp.net-coreapi-versioningaspnet-api-versioning

I cant show the API versions in response header with ApiVersioning .net Core


I follow the instruction REST API versioning with ASP.NET Core to show My API version in the response header.

This is my Configuration code:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvc().AddNewtonsoftJson();
        services.AddMvc(opt =>
        {

        services.AddRouting(env => env.LowercaseUrls = true);
        services.AddApiVersioning(opt => {
            opt.ApiVersionReader = new MediaTypeApiVersionReader();
            opt.AssumeDefaultVersionWhenUnspecified = true;
            opt.ReportApiVersions = true;
            opt.DefaultApiVersion = new ApiVersion(1, 0);
            opt.ApiVersionSelector = new CurrentImplementationApiVersionSelector(opt);
        });
    }

and this is my Controller :

[Route("/")]
[ApiVersion("1.0")]
public class RootController:Controller
{
    [HttpGet(Name =nameof(GetRoot))]
    public IActionResult GetRoot()
    {
        var response = new { href = Url.Link(nameof(GetRoot),null) };
        return Ok(response);
    }
}

when I test my API with postman I got this result :

enter image description here

I don't know why opt.ReportApiVersions = true; doesn't work.


Solution

  • The reason why it behaves this way is to disambiguate an API controller from a UI controller. In ASP.NET Core, there's not really any other built-in way to do so as - a controller is a controller.

    There are a few other ways to change this behavior:

    • Opt out with options.UseApiBehavior = false as the was the case before [ApiController]
    • Add a custom IApiControllerSpecification that identifies an API controller (there's a built-in implementation that understands [ApiController])
    • Replace the default IApiControllerFilter service, which is really just an aggregation over all registered IApiControllerSpecification implementations

    I hope that helps