swagger排除某些接口

    /// <summary>
    /// ignore some api on swagger.json
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class SwaggerIgnoreAttribute : Attribute
    {

    }

    /// <summary>
    /// 过滤具备SwaggerIgnore特性的api
    /// </summary>
    public class SwaggerIgnoreFilter : Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter
    {

        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var ignoreApis = context.ApiDescriptions.Where(wh => wh.CustomAttributes().Any(any => any is SwaggerIgnoreAttribute));
            if (ignoreApis != null)
            {
                foreach (var ignoreApi in ignoreApis)
                {
                    swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath);
                }
            }
        }
    }

需要排除的Controller类加入[SwaggerIgnore]属性

 

Startup.ConfigureServices:

            services.AddSwaggerGen(c =>
            {
                c.DocumentFilter<SwaggerIgnoreFilter>();

            });

 

posted @ 2020-12-21 17:45  IWing  阅读(2852)  评论(0编辑  收藏  举报