目录
基于 Swashbuckle.AspNetCore ,根据SwaggerGenerators生成的文档生成 MarkDown 文档。
文档功能:
- JSON 数据格式展示 Request 、Response 数据结构(支持实体多级引用)
- JSON 数据格式展示 Request Body 、Response Body 示例参数
- 支持原生IDocumentFilter、IOperationFilter、IParameterFilter过滤器
1、SwaggerDoc引用
主要接口
/// <summary>
/// ISwaggerDocGenerator
/// </summary>
public interface ISwaggerDocGenerator
{
/// <summary>
/// 获取Swagger流文件
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
Task<MemoryStream> GetSwaggerDocStreamAsync(string name);
/// <summary>
/// 获取Swagger MarkDown源代码
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
string GetSwaggerDoc(string name);
}
2、Startup配置
注册SwaggerDoc服务
services.AddSwaggerDoc();//(用于MarkDown生成)
注册Swagger服务
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Swagger API 示例文档", Version = "v1",Description="API文档全部由代码自动生成" });
c.IncludeXmlComments("Samples.xml");
});
引用Swagger中间件
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Samples v1"));
3、生成MarkDown
/// <summary>
/// SwaggerController
/// </summary>
[ApiController]
public class SwaggerController : ControllerBase
{
/// <summary>
/// API文档导出
/// </summary>
[HttpGet("/doc")]
public async Task<IActionResult> Doc([FromServices] ISwaggerDocGenerator swaggerDocGenerator, [FromServices] IWebHostEnvironment environment)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var stream = await swaggerDocGenerator.GetSwaggerDocStreamAsync("v1");
stopwatch.Stop();
var log = "Swagger文档导出成功,耗时" + stopwatch.ElapsedMilliseconds + "ms";
Debug.WriteLine(log);
var mime = "application/octet-stream";
var name = "SwaggerDoc.md";
return File(stream.ToArray(), mime, name);
}
}
4、生成示例
5、MarkDown转PDF
我是用的是 typora 编辑器,下载 pandoc 插件可以实现Marddown格式转换为PDF功能(免费)
如果需要样式调整,可以去theme 选选
完整项目示例
地址(可以直接运行): https://github.com/lwc1st/SwaggerDoc