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

.NET7中如何在不同JSON序列化场景下选择性排除属性

问题描述

现有如下C# POCO类:

public class Foo {
   public string PartitionKey => $"foo-{Bar}";
   public string Bar { get; set; }
}

需求说明:

  • 将该类序列化为JSON存入Azure Cosmos DB时,必须保留PartitionKey属性
  • 通过ASP.NET WebAPI返回给客户端时,需要排除PartitionKey属性
  • 技术栈限定为.NET 7 + System.Text.Json,要求实现方式最简,无需自定义JsonSerializer,优先通过属性或配置实现

预期序列化结果:

  • 数据库存储的JSON:
{
  "partitionKey": "foo-alice",
  "bar": "alice"
}
  • API响应的JSON:
{
  "bar": "alice"
}

最简实现方案

1. 统一JSON属性命名(匹配Cosmos DB预期)

先给POCO类的属性添加[JsonPropertyName]特性,确保序列化后的键名符合预期格式:

using System.Text.Json.Serialization;

public class Foo {
    [JsonPropertyName("partitionKey")]
    public string PartitionKey => $"foo-{Bar}";
    [JsonPropertyName("bar")]
    public string Bar { get; set; }
}

2. 配置WebAPI的序列化规则

在ASP.NET Core项目的Program.cs中,通过配置JSON序列化选项,让WebAPI返回响应时自动忽略PartitionKey属性:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolverModifier = typeInfo =>
        {
            if (typeInfo.Type == typeof(Foo))
            {
                var partitionKeyProperty = typeInfo.Properties.FirstOrDefault(p => p.Name == nameof(Foo.PartitionKey));
                if (partitionKeyProperty != null)
                {
                    // 设置该属性不参与API响应的序列化
                    partitionKeyProperty.ShouldSerialize = _ => false;
                }
            }
            return typeInfo;
        };
    });

实现原理

  • 存储到Cosmos DB时,直接使用默认的JsonSerializer.Serialize(或Cosmos DB SDK自带的序列化逻辑),默认会包含所有属性,满足保留PartitionKey的需求
  • WebAPI响应时,通过TypeInfoResolverModifier动态修改Foo类的序列化契约,强制排除PartitionKey属性,无需修改业务代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:50:30