ASP.NET Core 8 Web API:如何添加版本控制?

Enr*_*ico 11 c# asp.net-core asp.net-core-webapi .net-8.0

我正在创建一个新的 ASP.NET Core 8 Web API。在我之前使用 .NET 6 或 .NET 7 的项目中,我可以使用:

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

services.AddVersionedApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";
    options.SubstituteApiVersionInUrl = true;
});
Run Code Online (Sandbox Code Playgroud)

现在,该软件包Microsoft.AspNetCore.Mvc.ApiExplorer已被弃用,我将其替换为新软件包Asp.Versioning.Mvc.ApiExplorer,但没有AddVersionedApiExplorer.

在此输入图像描述

在 Swagger 的配置中,我有以下代码:

public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
    private readonly IApiVersionDescriptionProvider _provider;

    public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
    {
        _provider = provider;
    }

    public void Configure(SwaggerGenOptions options)
    {
        foreach (var description in _provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(
                description.GroupName,
                CreateVersionInfo(description));
        }
    }

    public void Configure(string name, SwaggerGenOptions options)
    {
        Configure(options);
    }

    private static OpenApiInfo CreateVersionInfo(
        ApiVersionDescription description)
    {
        var info = new OpenApiInfo()
        {
            Title = "Test API",
            Version = description.ApiVersion.ToString(),
            Description = "This is a test API.",
        };

        if (description.IsDeprecated)
        {
            info.Description += " This API version has been deprecated.";
        }

        return info;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行该应用程序时,我收到此错误

尝试激活“Middletier.Api.Extensions.Configuration.ConfigureSwaggerOptions”时无法解析类型“Asp.Versioning.ApiExplorer.IApiVersionDescriptionProvider”的服务。

在此输入图像描述

我该如何修复它?

Gur*_*ron 21

AddApiVersioning工作方式有点不同(它返回IApiVersioningBuilder)。安装Asp.Versioning.Mvc.ApiExplorer它将允许调用AddApiExplorer返回IApiVersioningBuilderAddApiVersioning

builder.Services.AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
    })
    .AddApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
    });
Run Code Online (Sandbox Code Playgroud)

请参阅快速入门示例和此问题 - ApiVersion attribute notworking in .NET 8