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

.NET 6 Web API中Newtonsoft.Json的JsonIgnore属性失效求助

问题原因及解决方案

你的问题核心是:.NET 6+的Web API默认使用System.Text.Json作为JSON序列化器,而你用的是Newtonsoft.Json(Json.NET)的[JsonIgnore]属性,两者不属于同一序列化体系,所以属性不会生效。[IgnoreDataMember]是针对DataContractSerializer的,同样不适用于默认的序列化器。

下面给出两种可行的解决办法:

办法一:改用System.Text.Json的[JsonIgnore]

直接替换属性为System.Text.Json对应的版本,需要先引入命名空间:

using System.Text.Json.Serialization;

public class xyz
{
    [JsonIgnore]
    public string AppNo { get; set; }
    public int dpd { get; set; }
    public string email { get; set; }
    public string address { get; set; }
    public int currency { get; set; }
}

修改后重新运行,AppNo就不会出现在JSON输出里了。

办法二:配置项目使用Newtonsoft.Json作为序列化器

如果你依赖Newtonsoft的其他特性,必须用它的话,按以下步骤操作:

  1. 安装NuGet包:Microsoft.AspNetCore.Mvc.NewtonsoftJson
  2. 在Program.cs中修改服务配置,添加NewtonsoftJson支持:
var builder = WebApplication.CreateBuilder(args);

// 添加控制器并启用Newtonsoft.Json序列化
builder.Services.AddControllers()
    .AddNewtonsoftJson();

var app = builder.Build();

// 其他中间件配置(如路由、授权等)保持不变

app.MapControllers();

app.Run();

配置完成后,你原来的Newtonsoft.Json的[JsonIgnore]就会正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:35:46