iServiceCollection”不包含“addVersionedApiExplorer”的定义

Lup*_*upa 16 c# swagger asp.net-core nswag

在 Asp.Net Core v3.1 api、Swagger v3.0 中,当我声明了多个版本时,Swagger UI 无法加载 API 定义。

编辑:同样来自 NuGet:

Mcrosoft.AspNetCore.Mvc.版本控制 v4.1.1

NSwag.AspNetCore v13.7.0

根据 NSwag 的文档,我意识到我必须将以下内容添加到我的“Startup.ConfigureServices()”中:

services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ApiVersionReader = new UrlSegmentApiVersionReader();
})
.AddMvcCore()
.AddVersionedApiExplorer(options =>
{
    options.GroupNameFormat = "VVV";
    options.SubstituteApiVersionInUrl = true;
});
Run Code Online (Sandbox Code Playgroud)

但是 '''AddVersionedApiExplore()''' 在那里不可用...然后我发现这个 ApiExplorerOptions wiki其中指出(我是这样理解的)自 Asp.Net Core 3.0 以来,它的用法是:

services.AddVersionedApiExplorer( options => { /* configure options */ } );
Run Code Online (Sandbox Code Playgroud)

但我最终得到的错误'IServiceCollection'不包含定义'AddVersionedApiExplorer'

顺便说一句,每个版本的 Postman 服务的所有路径都运行良好,swagger 的页面加载并显示我声明的两个版本,但无法加载它们的定义。

有人可以指出我正确的方向吗?

Adn*_*nan 37

从开始.Net 6,该包现在被称为Asp.Versioning.Mvc.ApiExplorer.

相同的包在.Net 7.

使用新的最小方法构建应用程序:


var apiVersioningBuilder = builder.Services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    // Use whatever reader you want
    options.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
                                    new HeaderApiVersionReader("x-api-version"),
                                    new MediaTypeApiVersionReader("x-api-version"));
}); // Nuget Package: Asp.Versioning.Mvc

apiVersioningBuilder.AddApiExplorer(options =>
{
    // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
    // note: the specified format code will format the version as "'v'major[.minor][-status]"
    options.GroupNameFormat = "'v'VVV";

    // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
    // can also be used to control the format of the API version in route templates
    options.SubstituteApiVersionInUrl = true;
}); // Nuget Package: Asp.Versioning.Mvc.ApiExplorer
Run Code Online (Sandbox Code Playgroud)


Lup*_*upa 13

解决方案:AddVersionedApiExplore 位于Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer NuGet 包中。

  • 此包 Microsoft.AspNetCore.Mvc.Versioning.ApiExploreri 自昨天起已弃用。只需使用@Adnan 的答案... (3认同)
  • 谢谢@Jay,我的错是信任“NuGetRecommender”扩展。我花了几个小时,当我输入 services.AddVersionedApiExplorer() 时,它没有像在其他类似情况下那样建议安装任何软件包。抱歉:/ (2认同)