Home > Enterprise >  InvalidOperationException: Register the constraint type with 'Microsoft.AspNetCore.Routing.Rout
InvalidOperationException: Register the constraint type with 'Microsoft.AspNetCore.Routing.Rout

Time:11-01

Recently a change was made to our code and I'm stuck as far as how to fix it. Originally we had the routes on our controllers set up as

[Route("api/v1/product/[controller]")]
[ApiController]

And this was modified to accomodate versioning as follows:

[Route("api/v{version:apiVersion}/product/[controller]")]
[ApiVersion("1.0")]

And now the app is throwing the following error:

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

The dev that implemented this is unavailable, so I'm looking for suggestions until they get back. Seems to work fine in our dev environment but can't run it locally. We're running .NET 6 and this is the startup code:

  if (enableSwagger)
  {
    services
    .AddSwaggerGen(c =>
    {
      c.SwaggerDoc(EngineExtensions.API_ENGINE_VERSION, new Microsoft.OpenApi.Models.OpenApiInfo { Title = EngineExtensions.API_ENGINE_NAME, Version = EngineExtensions.API_ENGINE_VERSION });
      c.CustomSchemaIds(type => type.FullName);
    });
  }

referencing this in appsettings

"api_engine_version": "v1",

CodePudding user response:

Please make sure that you are configuring versioning in Startup.cs. You should be using AddApiVersioning and AddVersionedApiExplorer extension methods of IServiceCollection (in ConfigureServices method). An example would be:

 services.AddApiVersioning(config =>
        {
            // Specify the default API Version as 1.0
            config.DefaultApiVersion = new ApiVersion(1, 0);
            // Advertise the API versions supported for the particular endpoint (through 'api-supported-versions' response header which lists all available API versions for that endpoint)
            config.ReportApiVersions = true;
        });

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

CodePudding user response:

I have encountered the same problem.

You need to make sure that you are using Microsoft.AspNetCore.Mvc.Versioning.

Just add AddControllers() and AddApiVersioning() to Program.cs

Complete code:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddApiVersioning();

Referenced links:

https://www.infoworld.com/article/3562355/how-to-use-api-versioning-in-aspnet-core.html

  • Related