如何使用ASP.NET核心Web API在SwaggerUI中设置默认版本

aiazj4mn  于 2022-11-06  发布在  .NET
关注(0)|答案(1)|浏览(315)

我已经设置了两个Swagger文档版本/描述:

builder.Services.AddSwaggerGen(setupAction =>
{
    setupAction.SwaggerGeneratorOptions.SwaggerDocs.Add("v1", new OpenApiInfo()
    {
        Version = "v1",
        Title = "MY API version 1",
        Description = "This is my API in version1",
    });
    setupAction.SwaggerGeneratorOptions.SwaggerDocs.Add("v2", new OpenApiInfo()
    {
        Version = "v2",
        Title = "MY API version 2",
        Description = "This is my API in version2",
    });

我可以在以下位置看到生成的文档:
请输入您的密码

{
  "openapi": "3.0.1",
  "info": {
    "title": "MY API version 1",
    "description": "This is my API in version1",
    "version": "v1"
  },
  "paths": {

您的位置:首页〉〉

{
  "openapi": "3.0.1",
  "info": {
    "title": "MY API version 2",
    "description": "This is my API in version2",
    "version": "v2"
  },
  "paths": {

但是,我无法找到SwaggerUI从版本v2开始时如何设置默认版本,以及为什么“选择定义”下拉菜单中只有版本v1可用:

tmb3ates

tmb3ates1#

这里有一个完整的工作演示,如果有任何遗漏,您可以遵循:
1.配置SwaggerOptions以注册所有API版本:

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

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

    /// <summary>
    /// Configure each API discovered for Swagger Documentation
    /// </summary>
    /// <param name="options"></param>
    public void Configure(SwaggerGenOptions options)
    {
        // add swagger document for every API version discovered
        foreach (var description in _provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(
                description.GroupName,
                CreateVersionInfo(description));
        }
    }

    /// <summary>
    /// Configure Swagger Options. Inherited from the Interface
    /// </summary>
    /// <param name="name"></param>
    /// <param name="options"></param>
    public void Configure(string name, SwaggerGenOptions options)
    {
        Configure(options);
    }

    /// <summary>
    /// Create information about the version of the API
    /// </summary>
    /// <param name="description"></param>
    /// <returns>Information about the API</returns>
    private OpenApiInfo CreateVersionInfo(
            ApiVersionDescription desc)
    {
        var info = new OpenApiInfo()
        {
            Title = ".NET Core (.NET 6) Web API",
            Version = desc.ApiVersion.ToString()
        };

        if (desc.IsDeprecated)
        {
            info.Description += " This API version has been deprecated. Please use one of the new APIs available from the explorer.";
        }

        return info;
    }
}

2.Program.cs:
注意:请务必安装Microsoft.AspNetCore.Mvc.VersioningMicrosoft.AspNetCore.Mvc.Versioning.ApiExplorer

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddApiVersioning(o => {
    o.ReportApiVersions = true;
    o.AssumeDefaultVersionWhenUnspecified = true;
    o.DefaultApiVersion = new ApiVersion(1, 0);
});
builder.Services.AddVersionedApiExplorer(setup =>
{
    setup.GroupNameFormat = "'v'VVV";
    setup.SubstituteApiVersionInUrl = true;
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.ConfigureOptions<ConfigureSwaggerOptions>();   // register the options here....

var app = builder.Build();
var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseSwaggerUI(options =>
    {
        foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions.Reverse())
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
                description.GroupName.ToUpperInvariant());
        }
    });
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

3.Controller:

namespace SwaggerProj.Controllers
{
    [ApiController]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class WeatherForecastController : ControllerBase
    {            
        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult Get()
        {
            return Ok("v1");
        }
    }
}

namespace SwaggerProj.Controllers.v2
{
    [ApiVersion("2.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult Get()
        {
            return Ok("v2");
        }
    }
}

4.Result:

相关问题