InvalidOperationException:使用"Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap"注册约束类型



最近我们的代码发生了更改,我一直不知道如何修复它。最初,我们将控制器上的路由设置为

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

并对其进行了修改,以适应如下版本控制:

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

现在该应用程序抛出以下错误:

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

实现这一点的开发人员不可用,所以我正在寻找建议,直到他们回来。在我们的开发环境中似乎工作得很好,但无法在本地运行。我们正在运行.NET 6,这是启动代码:

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);
});
}

在appsettings 中引用此

"api_engine_version": "v1",

请确保您正在Startup.cs中配置版本控制。您应该使用IServiceCollection的AddApiVersioning和AddVersionedApiExplorer扩展方法(在ConfigureServices方法中(。例如:

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;
});

我也遇到了同样的问题。

您需要确保使用的是Microsoft.AspNetCore.Mvc.Version.

只需将AddControllers((和AddApiVersioning((添加到Program.cs

完整代码:

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

参考链接:

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

最新更新