约束引用“ApiVersion”无法解析为类型

问题描述 投票:0回答:3

约束参考异常:

嗨, 我正在使用带有版本控制的 .Net 6 Web API,我的版本控制在 Swagger 中工作得很好,但是当我从 MVC Framework (.NET 6) 引用我的 API 时,我收到一个异常:

InvalidOperationException:约束引用“apiVersion”无法解析为类型。使用“Microsoft.AspNetCore.Routing.RouteOptions.ConstraintMap”注册约束类型。

    public static IServiceCollection AddApiVersioningConfig(this IServiceCollection services)
    {
        services.AddApiVersioning(cfg =>
        {
            cfg.DefaultApiVersion = new ApiVersion(1, 0);
            cfg.AssumeDefaultVersionWhenUnspecified = true;             // In case if the user doesn't specify the version, so we assume to use the default one (v1)
            cfg.ReportApiVersions = true;                               // This will mention which API the user is currently using (Header).
           

            // 1-  api/v1/clients/ => In order to read the segment that contains the version eg.

            // 2- api-version : 1.0 => In case the user provides the version as header  

            // 3- ?api-version=1.0 => From query approach

            cfg.ApiVersionReader = ApiVersionReader.Combine(
                new HeaderApiVersionReader("X-version"),
                new QueryStringApiVersionReader("api-version"),
                new UrlSegmentApiVersionReader(),
                new MediaTypeApiVersionReader("ver"));
        });

        return services;
    }
}

app.UseSwaggerUI(opt =>
{
    var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

    foreach (var description in provider.ApiVersionDescriptions)
    {
        opt.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",  description.ApiVersion.ToString());
    }
});

非常感谢您的帮助:)

卡利王

api-versioning
3个回答
10
投票

我在部署在 Azure 应用服务上的 Web API 上收到相同的错误,但在本地没有收到错误。

错误:

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

解决方案:

Startup.cs
文件中,我添加了以下行:

services.AddApiVersioning();

该方法位于

Microsoft.Extensions.DependencyInjection

通过该更改重新部署到我们的 Azure 应用服务后,一切都按预期运行。


1
投票

在program.cs中添加以下代码

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

0
投票

问题可能是您使用了错误的 nuget 包。 你有 Asp.Versioning.WebApi 并且你有 Asp.Versioning.Mvc

如果您的 Api 使用原始 MVC 控制器,则需要使用 Asp.Versioning.Mvc,而不是 Asp.Versioning.WebApi。

https://www.nuget.org/packages/Asp.Versioning.Mvc/ https://www.nuget.org/packages/Asp.Versioning.WebApi/

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.