asp.net core 3.1 使用Swashbuckle.AspNetCore.SwaggerGen 5.6.3 实现实体类标记隐藏参数

using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Reflection;

namespace Com.macao.electron.Utils
{

    /// <summary>
    /// 标记实体类属性删除(不能在控制器中使用)
    /// </summary>
    public class SwaggerExcludeFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext schemaFilterContext)
        {
            if (schema.Properties.Count == 0)
                return;

            const BindingFlags bindingFlags = BindingFlags.Public |
                                              BindingFlags.NonPublic | BindingFlags.IgnoreCase |
                                              BindingFlags.Instance;
            var memberList = schemaFilterContext.Type
                                .GetFields(bindingFlags).Cast<MemberInfo>()
                                .Concat(schemaFilterContext.Type
                                .GetProperties(bindingFlags));

            var memberAttr = schemaFilterContext.Type.GetCustomAttributes(typeof(SwaggerParamAttribute), false).FirstOrDefault();

            var excludedList = memberList.Where(m =>
                                                m.GetCustomAttribute<SwaggerParamAttribute>()
                                                != null)
                                         .Select(m =>
                                             (m.GetCustomAttribute<JsonPropertyAttribute>()
                                              ?.PropertyName
                                              ?? m.Name.ToCamelCase()));
            foreach (var excludedName in excludedList)
            {
                if (schema.Properties.ContainsKey(excludedName))
                    schema.Properties.Remove(excludedName);
            }
        }
    }

    internal static class StringExtensions
    {
        internal static string ToCamelCase(this string value)
        {
            if (string.IsNullOrEmpty(value)) return value;
            return char.ToLowerInvariant(value[0]) + value.Substring(1);
        }
    }
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class SwaggerParamAttribute : Attribute
    {
        public SwaggerParamAttribute()
        {

        }

    }
}

在Startup文件中

services.AddSwaggerGen(option =>
            {
              option.SchemaFilter<SwaggerExcludeFilter>();
            
            });


本文作者:admin

本文链接:https://www.javalc.com/post/44.html

版权声明:本篇文章于2020-11-30,由admin发表,转载请注明出处:分享你我。如有疑问,请联系我们

vue 自定义全局指令

发表评论

取消
扫码支持