Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 216
JaimeCamargo Avatar asked Oct 24 '19 19:10

JaimeCamargo


2 Answers

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

like image 64
Xueli Chen Avatar answered Nov 12 '22 22:11

Xueli Chen


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
{
   ...
}
like image 44
circa94 Avatar answered Nov 12 '22 23:11

circa94