ASP .NET CORE优雅地使用Swagger 并生成接口文档
1.生成文档文件
注意:所有接口引用到的类库都要生成否则会注释不全
2.让Swagger加载文档文件
static List<string> XmlCommentsFilePath
{
get
{
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
DirectoryInfo d = new DirectoryInfo(basePath);
FileInfo[] files = d.GetFiles("*.xml");
var xmls = files.Select(a => Path.Combine(basePath, a.FullName)).ToList();
return xmls;
}
}
public static class SwaggerGenSetUp
{
/// <summary>
/// Swagger注释
/// </summary>
/// <param name="services"></param>
public static void AddSwaggerGenSetUp(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "北向接口调用示例", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//让swagger加载所有的xml 文档文件****
foreach (var item in XmlCommentsFilePath)
{
c.IncludeXmlComments(item);
}
});
services.AddScoped<SwaggerGenerator>();
}
}
3.加载swagger设置
//swagger设置
builder.Services.AddSwaggerGenSetUp();
4.将swagger.json转换成word文档
使用json转doc文档工具
https://tools.kalvinbg.cn/dev/swagger2word