在 Swagger 中自定义版本号

Pra*_*mar 1 c# swagger .net-core asp.net-core-webapi asp.net-core-6.0

我正在使用 dotnet core webapi 的默认 swagger 实现。每当版本号从右上角的“选择定义”下拉列表中更改时,我希望显示实际版本号而不是模板。

因此,例如,当从下拉列表中选择 v2 时,它应该显示为这样

在此输入图像描述

而不是这个,

在此输入图像描述

有什么线索可以做到这一点吗?

bug*_*sen 6

您可以使用Microsoft.AspNetCore.Mvc.Versioning自定义 swagger 过滤器。

创建自定义文档过滤器;

public class ReplaceVersionWithExactValueInPathFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var paths = swaggerDoc.Paths;

        swaggerDoc.Paths = new OpenApiPaths();

        foreach (var path in paths)
        {
            var key = path.Key.Replace("v{version}", swaggerDoc.Info.Version);

            var value = path.Value;

            swaggerDoc.Paths.Add(key, value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将版本控制和 swagger 服务添加到您的服务集合中;

services.AddApiVersioning(config =>
{
    // Specify the default API Version
    config.DefaultApiVersion = new ApiVersion(1, 0);

    // If the client hasn't specified the API version in the request, use the default API version number 
    config.AssumeDefaultVersionWhenUnspecified = true;

    // Advertise the API versions supported for the particular endpoint
    config.ReportApiVersions = true;
});

//Adding swagger services
services.AddSwaggerGen(options =>
{
    //other configurations 

    options.SwaggerDoc("v1.0", new OpenApiInfo
    {
        Version = "v1.0",
        Title = "Your Api Title",
        Description = "Your Api Description",
        TermsOfService = new Uri("https://yourcompany.com"),
        Contact = new OpenApiContact { Name = "Your Company", Email = "info@yourcompany.com", Url = new Uri("https://yourcompany.com") },
        License = new OpenApiLicense { Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT") }
    });

    options.SwaggerDoc("v2.0", new OpenApiInfo
    {
        Version = "v2.0",
        Title = "Your Api Title",
        Description = "Your Api Description",
        TermsOfService = new Uri("https://yourcompany.com"),
        Contact = new OpenApiContact { Name = "Your Company", Email = "info@yourcompany.com", Url = new Uri("https://yourcompany.com") },
        License = new OpenApiLicense { Name = "MIT", Url = new Uri("https://opensource.org/licenses/MIT") }
    });
        
    options.DocumentFilter<ReplaceVersionWithExactValueInPathFilter>();

    //other configurations 
});
Run Code Online (Sandbox Code Playgroud)

寄存器SwaggerSwaggerUI中间件;

app.UseSwagger(c =>
{
    c.SerializeAsV2 = true;
    c.RouteTemplate = "api/docs/{documentName}/docs.json";
}).UseSwaggerUI(c =>
{
    c.SwaggerEndpoint($"/api/docs/v1.0/docs.json", "v1.0");
    c.SwaggerEndpoint($"/api/docs/v2.0/docs.json", "v2.0");
});
Run Code Online (Sandbox Code Playgroud)

然后配置你的控制器;

[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class TestsController : ControllerBase
{

    [HttpPost("Test")]
    [ApiVersion("1.0")]
    [ApiExplorerSettings(GroupName = "v1.0")]
    public IActionResult TestV1()
    {
        return Ok();
    }
    
    [HttpPost("Test")]
    [ApiVersion("2.0")]
    [ApiExplorerSettings(GroupName = "v2.0")]
    public IActionResult TestV2()
    {
        return Ok();
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您想从文档中删除版本标题,您应该使用它;

public class VersionHeaderFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
         if (operation.Parameters != null)
         {
             var versionParameter = operation.Parameters.SingleOrDefault(p => p.Name == "version");

             if (versionParameter != null) 
                 operation.Parameters.Remove(versionParameter);
         }
    }
}
Run Code Online (Sandbox Code Playgroud)
services.AddSwaggerGen(options =>
{
     //other configurations 

     options.OperationFilter<VersionHeaderFilter>();

     //other configurations 
});
Run Code Online (Sandbox Code Playgroud)

这应该有效。