You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NSwag运行时过滤/忽略类属性?(附Swashbuckle实现示例)

在NSwag中实现运行时移除/忽略属性

你在Swashbuckle中通过ISchemaFilter实现的基于自定义属性和配置级别动态移除Schema属性的功能,完全可以在NSwag中实现,核心是使用NSwag的ISchemaProcessor接口(对应Swashbuckle的ISchemaFilter)。

实现步骤

1. 注册Schema处理器

在配置NSwag的AddOpenApiDocument时,添加自定义的Schema处理器:

services.AddOpenApiDocument(config =>
{
    var serviceProvider = services.BuildServiceProvider();
    config.SchemaProcessors.Add(new SwaggerExcludeSchemaProcessor(serviceProvider.GetRequiredService<IServiceConfig>()));
});

2. 编写自定义Schema处理器

实现ISchemaProcessor接口,逻辑和你在Swashbuckle中的Filter基本一致,仅需适配NSwag的对象模型:

// 通过IoC注入IServiceConfig
public class SwaggerExcludeSchemaProcessor(IServiceConfig config) : ISchemaProcessor
{
    private readonly int _ignoreLevel = config.IgnoreLevel;

    public void ProcessSchema(SchemaProcessorContext context)
    {
        if (context.Schema.Properties == null || context.Schema.Properties.Count == 0)
            return;

        var type = context.Type;
        var properties = type.GetProperties();

        foreach (var propertyInfo in properties)
        {
            if (propertyInfo.GetCustomAttribute<IgnoreFeatureAttribute>() is { } ignoreAttr && ignoreAttr.Level < _ignoreLevel)
            {
                // 忽略大小写匹配Schema中的属性键
                var propertyKey = context.Schema.Properties.Keys.FirstOrDefault(k => 
                    k.Equals(propertyInfo.Name, StringComparison.OrdinalIgnoreCase));
                
                if (!string.IsNullOrEmpty(propertyKey))
                {
                    // 移除属性
                    context.Schema.Properties.Remove(propertyKey);
                    
                    // 同步移除Required列表中的对应项(如果存在)
                    if (context.Schema.Required?.Contains(propertyKey) == true)
                    {
                        context.Schema.Required.Remove(propertyKey);
                    }
                }
            }
        }
    }
}

关键说明

  • NSwag的ISchemaProcessor和Swashbuckle的ISchemaFilter作用完全一致,都是在Schema生成阶段做自定义修改。
  • 需要额外处理Schema.Required集合,避免出现“属性已移除但仍标记为必填”的文档不一致问题。
  • 逻辑判断部分和你原有代码完全兼容,无需修改IgnoreFeatureAttribute的定义。

内容的提问来源于stack exchange,提问作者Peter Poulsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:43:11