.NET 中的 Swagger 文檔排序設(shè)置
Swagger的API默認(rèn)排序往往達(dá)不到效果,甚至設(shè)置了Action排序也沒有作用。這里直接給出代碼,關(guān)鍵在于 IDocumentFilter 實(shí)現(xiàn)。
注意 DocumentFilter 注冊(cè)要放在尾部,否則獲取不到分組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); }// 設(shè)置分組排序 c.DocumentFilter<OrderTagsDocumentFilter>(); // 設(shè)置API排序 c.OrderActionsBy(desc => desc.RelativePath); });
/// <summary> /// 文檔按控制器分組 /// </summary> public class OrderTagsDocumentFilter : IDocumentFilter { /// <summary> /// 設(shè)置 /// </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(); } }
浙公網(wǎng)安備 33010602011771號(hào)