gpt4 book ai didi

swagger - .Net 6 Web Api Swagger 版本控制问题

转载 作者:行者123 更新时间:2023-12-05 03:22:35 25 4
gpt4 key购买 nike

正如标题所示,我有一个 .net 6 web api,我正在尝试向其添加版本控制,但 swagger (swashbuckle) 似乎不明白发生了什么。

Program.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddApiVersioning(setup =>
{
setup.DefaultApiVersion = new ApiVersion(1, 0);
setup.AssumeDefaultVersionWhenUnspecified = true;
setup.ReportApiVersions = true;
});

ConfigureServices(builder.Services);

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"/swagger/v1/swagger.json", $"v1");
c.SwaggerEndpoint($"/swagger/v2/swagger.json", $"v2");
});

app.Run();

void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();

services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = false;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
});
services.AddSwaggerGen();
}

我已经像这样注释了我的 Controller :

[ApiVersion("1.0")]
[Route("api/v1/[controller]")]
[ApiController]
public class MessageController : ControllerBase

[ApiVersion("2.0")]
[Route("api/v2/[controller]")]
[ApiController]
public class MessageController : ControllerBase

生成的 swagger 文档如下所示:

enter image description here

如果我从下拉列表中选择 v2,我会得到:

enter image description here

安装的 Nuget 包和版本是:

enter image description here

谁能告诉我哪里出错了。

最佳答案

您需要自己添加 swagger 文档,而不仅仅是它们的 UI。在您的 AddSwaggerGen 方法中,添加如下内容:

services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "My API" });
c.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "My API" });
});

关于swagger - .Net 6 Web Api Swagger 版本控制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72689867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com