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

从Json.Net迁移到System.Text.Json后Swagger请求不显示属性如何解决?

问题根因

ASP.NET Core默认的Swagger生成组件Swashbuckle对System.Text.Json的JsonIgnoreCondition.WhenWritingNull特性处理逻辑与Newtonsoft.Json不同:默认会将标注了该特性的属性直接从Swagger结构定义中移除,导致不在请求UI中展示。

解决方案

方案一:使用官方System.Text.Json适配包(推荐,适配Swashbuckle 5.0及以上版本)

  1. 首先安装适配NuGet包:
Install-Package Swashbuckle.AspNetCore.SystemTextJson
  1. 在Startup.cs的ConfigureServices方法中调整Swagger配置:
services.AddSwaggerGen(options =>
{
    // 保留你原有Swagger配置,比如文档标题、版本等
})
.AddSystemTextJsonSupport(options =>
{
    // 和全局System.Text.Json配置保持一致即可
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    // 关键配置:不自动隐藏仅标注了WhenWritingNull规则的属性
    options.IgnoreJsonIgnoreCondition = true;
});

方案二:自定义Schema过滤器(兼容所有版本)

如果你的Swashbuckle版本较低不支持方案一,可以通过自定义过滤器重写属性展示规则:

  1. 新增过滤器类:
using System.Linq;
using System.Text.Json.Serialization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class KeepJsonIgnoreWhenWritingNullPropertiesFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Properties == null || !schema.Properties.Any())
        {
            return;
        }

        // 查找所有标记了JsonIgnore且Condition为WhenWritingNull的属性
        var targetProperties = context.Type.GetProperties()
            .Where(prop => prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), false)
                .Cast<JsonIgnoreAttribute>()
                .Any(attr => attr.Condition == JsonIgnoreCondition.WhenWritingNull));

        foreach (var propertyInfo in targetProperties)
        {
            // 按你的序列化命名规则生成属性名,此处默认是驼峰命名
            var camelCasePropName = char.ToLowerInvariant(propertyInfo.Name[0]) + propertyInfo.Name[1..];
            if (!schema.Properties.ContainsKey(camelCasePropName))
            {
                // 生成属性对应的Schema并加入到返回结构中
                var propertySchema = context.SchemaGenerator.GenerateSchema(propertyInfo.PropertyType, context.SchemaRepository);
                schema.Properties.Add(camelCasePropName, propertySchema);
                // 非必填属性从必填列表中移除
                schema.Required?.Remove(camelCasePropName);
            }
        }
    }
}
  1. 在Swagger配置中注册过滤器:
services.AddSwaggerGen(options =>
{
    // 原有Swagger配置
    options.SchemaFilter<KeepJsonIgnoreWhenWritingNullPropertiesFilter>();
});

配置完成后,标注了[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]的属性就会正常在Swagger UI中展示,序列化时仍然会保留忽略null值的逻辑,和之前Newtonsoft.Json的表现完全一致。


内容的提问来源于stack exchange,提问作者Ayoub Salhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:57:03