因為場景需要,要把某些特定的api過濾掉,不允許顯示在swaggerui里,
具體操作步驟: 分為三步
步驟1: 創建Attribute
1 /// <summary> 2 /// ignore some api on swagger.json 3 /// </summary> 4 [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 5 public class SwaggerIgnoreAttribute : Attribute 6 { 7 8 }
步驟2:創建IDocumentFilter的實現類XXXFileter

/// <summary> /// 過濾具備SwaggerIgnore特性的api /// </summary> public class SwaggerIgnoreFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { var ignoreApis = context.ApiDescriptions.Where(wh => wh.ActionAttributes().Any(any => any is SwaggerIgnoreAttribute)); if (ignoreApis != null) { foreach (var ignoreApi in ignoreApis) { swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath); } } } }
步驟3:StartUp類中 Swagger的Config中使用過濾器
services.AddSwaggerGen( options => { options.DocumentFilter<SwaggerIgnoreFilter>(); });