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>();
});
评论区