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

ASP.NET Core中用属性实现JSON反序列化忽略Id(保留序列化)

解决方案

直接给Id属性添加[JsonIgnore]特性,并指定忽略条件为WhenReading,就能实现反序列化时忽略、序列化时保留的需求:

using System.Text.Json.Serialization;

public class ADto
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenReading)]
    public int Id { get; set; }
    public string Text { get; set; }
}

说明

  • 该特性依赖.NET 6及以上版本的System.Text.Json库(ASP.NET Core 6+默认集成)
  • JsonIgnoreCondition.WhenReading的作用:
    • 反序列化(处理前端请求数据)时,忽略Id属性,前端传入的Id值不会被赋值到DTO对象中
    • 序列化(返回响应给前端)时,正常输出Id属性,EF Core生成的Id会被返回给前端

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:57:13