Swagger+ReDoc最完善的API文档
开启swagger注释
-
项目设置勾选“文档文件”
-
加载文档文件
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new()
{
Title = builder.Environment.ApplicationName,
Version = "v1",
});
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, $@"{builder.Environment.ApplicationName}.xml");
c.IncludeXmlComments(xmlPath, true);
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
$"{builder.Environment.ApplicationName} v1"));
}
app.MapGet("/swag", () => "Hello Swagger!");
app.Run();
添加接口注释及ProducesResponseType
- 添加Remarks注释,可以更详细描述文档内容
- ProducesResponseType可以让调用者更清楚接口不同状态下返回的接口数据格式
swagger.json转swagger.yaml
- https://oktools.net/json2yaml
使用以上工具将swagger.json转为openapi.yaml文件
将部署Redoc 文档服务
- Github上clone Redoc项目
Redoc地址: https://github.com/Redocly/redoc
- 将 openapi.yaml 复制到demo目录中
-
运行npm run start
-
Redoc效果
完美的文档样式,再也不用文档发愁了