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

.Net 4.8 Web Api如何仅在Swagger UI响应显示null值且不修改全局序列化配置

实现方案

可以实现,该修改仅作用于Swagger元数据生成逻辑,完全不会影响全局API序列化配置。

实现步骤

  • 第一步:自定义ISchemaFilter实现类,强制Swagger在生成响应结构时保留所有可空属性
using Swagger.Net.Swagger;
using Swagger.Net.Annotations;
using Newtonsoft.Json;
using System.Reflection;
using System.Web.Http;

public class ShowNullPropertiesSchemaFilter : ISchemaFilter
{
    private static readonly JsonSerializerSettings GlobalJsonSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;

    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        // 仅处理响应模型的Schema,需要跳过示例值生成环节可自行补充判断逻辑
        if (schema?.properties == null || type == null) return;

        foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            // 适配全局属性命名规则(驼峰/原名)
            var serializedPropName = GlobalJsonSettings.ContractResolver.ResolvePropertyName(prop.Name);
            if (!schema.properties.ContainsKey(serializedPropName))
            {
                var propSchema = schemaRegistry.GetOrRegister(prop.PropertyType);
                propSchema.nullable = true;
                schema.properties.Add(serializedPropName, propSchema);
            }
            else
            {
                schema.properties[serializedPropName].nullable = true;
            }
        }
    }
}
  • 第二步:在Swagger配置中注册该过滤器,配置位置一般为App_Start/SwaggerConfig.cs
GlobalConfiguration.Configuration.EnableSwagger(c =>
{
    // 保留你原有所有Swagger配置不变
    c.SchemaFilter<ShowNullPropertiesSchemaFilter>();
});

注意事项

  • 该方案仅修改Swagger UI展示的响应结构,实际API返回仍然遵循全局NullValueHandling.Ignore规则,不会返回空值字段
  • 如果你需要排除示例值的null展示,只需要在Apply方法开头加对应上下文判断,符合示例值生成场景时直接返回即可
  • 针对单独加了[JsonProperty]特性配置了空值处理规则的属性,可以在过滤器中读取特性值做单独适配,避免冲突

内容的提问来源于stack exchange,提问作者Emin Hasanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:54:04