.NET 中的 Swagger 文档排序设置
Swagger的API默认排序往往达不到效果,甚至设置了Action排序也没有作用。这里直接给出代码,关键在于 IDocumentFilter 实现。
注意 DocumentFilter 注册要放在尾部,否则获取不到分组Tag信息
services.AddSwaggerGen(); services.AddOptions<SwaggerGenOptions>().Configure<IOptions<ProjectOptions>>((c, pOptions) => { c.SwaggerDoc("v1", new OpenApiInfo { Title = $"{proj.Code} ({proj.Profile})", Version = proj.Version, Description = proj.Title }); var basePath = AppContext.BaseDirectory; var xmlPath = Path.Combine(basePath, $"{proj.NsPrefix}.Model.xml"); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } xmlPath = Path.Combine(basePath, $"{proj.NsPrefix}.WebApi.xml"); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath, true); }// 设置分组排序 c.DocumentFilter<OrderTagsDocumentFilter>(); // 设置API排序 c.OrderActionsBy(desc => desc.RelativePath); });
/// <summary> /// 文档按控制器分组 /// </summary> public class OrderTagsDocumentFilter : IDocumentFilter { /// <summary> /// 设置 /// </summary> /// <param name="swaggerDoc"></param> /// <param name="context"></param> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Tags = swaggerDoc.Tags.OrderBy(x => x.Name).ToList(); } }