SwaggerIgnore

    /// <summary>
    /// SwaggerIgnoreAttribute
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method|AttributeTargets.Field|AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class SwaggerIgnoreAttribute : Attribute, IFilterMetadata
    {
        /// <summary>
        /// construct
        /// </summary>
        /// <param name="ignore"></param>
        public SwaggerIgnoreAttribute(bool ignore = true)
        {
            IgnoreApi = ignore;
        }
        /// <summary>
        /// 
        /// </summary>
        public string GroupName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public bool IgnoreApi { get; set; }
    }
    /// <summary>
    /// SwaggerIgnoreFilter
    /// </summary>
    public class SwaggerIgnoreFilter : Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            var ignoreApis =
                context.ApiDescriptions.Where(o =>
                {
                    if (o.TryGetMethodInfo(out MethodInfo methodInfo))
                    {
                        if (methodInfo == null) return false;
                        if (methodInfo.CustomAttributes.Any(any => any.AttributeType == typeof(SwaggerIgnoreAttribute)))
                        {
                            var attribute = methodInfo.GetCustomAttribute<SwaggerIgnoreAttribute>();
                            return attribute?.IgnoreApi ?? false;
                        }
                        else if (methodInfo.DeclaringType?.CustomAttributes.Any(any =>
                            any.AttributeType == typeof(SwaggerIgnoreAttribute)) ?? false)
                        {
                            var attribute = methodInfo.DeclaringType.GetCustomAttribute<SwaggerIgnoreAttribute>();
                            return attribute?.IgnoreApi ?? false;
                        }
                        return false;
                    }

                    return false;
                }).ToList();
            if (ignoreApis.Count > 0)
            {
                foreach (var ignoreApi in ignoreApis)
                {
                    swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath);
                }
            }
        }
    }
 services.AddSwaggerGen(
                options =>
                {
                    options.DocumentFilter<SwaggerIgnoreFilter>();
                });

 

posted @ 2023-03-28 13:33  向萧  阅读(55)  评论(0编辑  收藏  举报