在 swashbuckler 中,我用它来欺骗运行时删除/忽略属性:
services.AddSwaggerGen(c =>
{
c.SchemaFilter<SwaggerExcludeSchemaFilter>();
}
// IServiceConfig is injected through IoC
public class SwaggerExcludeSchemaFilter(IServiceConfig config) : ISchemaFilter
{
private int _ignoreLevel = config.IgnoreLevel;
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Properties == null || schema.Properties.Count == 0)
{
return;
}
var type = context.Type;
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
if (propertyInfo.GetCustomAttribute<IgnoreFeatureAttribute>() is { } ignoreFeatureAttribute)
{
if (ignoreFeatureAttribute.Level < _ignoreLevel)
{
if (schema.Properties.SingleOrDefault(x =>
x.Key.Equals(propertyInfo.Name, StringComparison.OrdinalIgnoreCase)) is var schemaProperty)
{
schema.Properties.Remove(schemaProperty.Key);
}
}
}
}
}
}
使用 NSwag 时有办法实现此目的吗?
我尝试过使用
DocumentProcessors
和 SchemaProcessors
但找不到忽略类属性的方法。
我最终这样做了:
public class ExcludeSchemaProcessor(IServiceConfig config) : ISchemaProcessor
{
private int _ignoreLevel = config.IgnoreLevel;
public void Process(SchemaProcessorContext context)
{
var type = context.Type;
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
if (propertyInfo.GetCustomAttribute<IgnoreFeatureAttribute>() is { } ignoreFeatureAttribute)
{
if (ignoreFeatureAttribute.Level < _ignoreLevel)
{
var camelCasePropertyName = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name.Substring(1);
context.Schema.Properties.Remove(camelCasePropertyName);
}
}
}
}
}
services.AddOpenApiDocument(configure =>
{
configure.SchemaSettings.SchemaProcessors.Add(_ioc.Resolve<IServiceConfig>());
});