侧边栏壁纸
博主头像
分享你我博主等级

行动起来,活在当下

  • 累计撰写 106 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

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

管理员
2020-11-30 / 0 评论 / 0 点赞 / 2 阅读 / 7092 字
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>();
            
            });


0

评论区