上一节
.NET 拓展Swagger之【添加注释】 - 掘金 (juejin.cn)
创建版本枚举
arduino
namespace ZhaoXi.WebSiteApi.Utility.SwaggerExt
{
public enum ApiVersion
{
V1,
V2
}
}
服务注册
erlang
typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
{
option.SwaggerDoc(version, new OpenApiInfo()
{
Title = $"标题",
Version = version,
Description = $"版本号为{version}"
});
});
csharp
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
// app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
foreach (string version in typeof(ApiVersion).GetEnumNames())
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"第【{version}】版本");
}
});
}
测试
为方法绑定版本
在类上添加:[ApiExplorerSettings(IgnoreApi = false,GroupName = nameof(Utility.SwaggerExt.ApiVersion.V1))]
测试
方法封装
将原先的方法抽出,封装到CustomSwaggerExt
类中
csharp
using Microsoft.OpenApi.Models;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
namespace ZhaoXi.WebSiteApi.Utility.SwaggerExt
{
public static class CustomSwaggerExt
{
public static void AddSwaggerExt(this IServiceCollection services)
{
#region Swagger的配置
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(option =>
{
// xml 文档文件绝对路径--读取根据控制器生成的xml文件
var file = Path.Combine(AppContext.BaseDirectory,
"ZhaoXi.WebSiteApi.xml");
// true: 显示控制器层注释
option.IncludeXmlComments(file, true);
// 对actuin的名称进行排序,如果有多个,就可以看到效果
option.OrderActionsBy(o => o.RelativePath);
typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
{
option.SwaggerDoc(version, new OpenApiInfo()
{
Title = $"标题",
Version = version,
Description = $"版本号为{version}"
});
});
});
#endregion
}
public static void UseSwaggerExt(this WebApplication app)
{
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
foreach (string version in typeof(ApiVersion).GetEnumNames())
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"第【{version}】版本");
}
});
}
}
}
}
替换Program.cs
代码