在运行时过滤/忽略 NSwag 中的属性

问题描述 投票:0回答:1

在 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
但找不到忽略类属性的方法。

c# openapi nswag
1个回答
0
投票

我最终这样做了:

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>());
});
© www.soinside.com 2019 - 2024. All rights reserved.