JaimeCamargo
JaimeCamargo

Reputation: 363

Versioning for WebApi on NetCore3

I'm taking the first steps in NetCore3. I have started a default webapi project in VS.NET 2019, this has created a controller called WeatherForecastController. I have tested the webapi and this returns a JSON with dummy information, so far so good.

Now, I'm trying to use the versioning by using the attribute Route in this way:

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public class WeatherForecastController : ControllerBase

But I ran into with this error:

InvalidOperationException: The constraint reference 'apiVersion' could not be resolved to a type. Register the constraint type with 'Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap'

According to the following URL:

https://www.koskila.net/how-to-resolve-build-failing-with-net-core-3-and-microsoft-aspnetcore-mvc-versioning/

I have installed the beta version of the library Microsoft.AspNet.WebApi.Versioning, but I keep getting the same error. Maybe I'm omitting something or I have a silly mistake but I can't identify or solve it.

Upvotes: 10

Views: 15311

Answers (2)

Xueli Chen
Xueli Chen

Reputation: 12695

Microsoft.AspNet.WebApi.Versioning is dependent on .NETFramework 4.5, not .Net Core . You need to install Microsoft.AspNetCore.Mvc.Versioning -Version 4.0.0-preview8.19405.7 which provides support for ASP.NET Core 3.0 in Package Manager Console as follows :

Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 4.0.0-preview8.19405.7

Then Add services.AddApiVersioning(); in ConfigureServices in Startup.cs

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

Reference :https://github.com/microsoft/aspnet-api-versioning/issues/499#issuecomment-521469545

Upvotes: 20

circa94
circa94

Reputation: 83

Do you have configured the versioning in your startup?

I am using this package: Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer

This is the code how it works for my API

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

services.AddVersionedApiExplorer(options =>
{
   options.GroupNameFormat = "'v'V";
   options.SubstituteApiVersionInUrl = true;
});

... and the controller:

[ApiVersion("1.0")]
[Route("api/v{ver:apiVersion}/[controller]")]
public class MyController : ControllerBase
{
   ...
}

Upvotes: 6

Related Questions