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

.NET Core 7.0项目Cosmos DB字典键大小写保存异常求助

解决.NET Core 7.0中Cosmos DB存储字典时保留键大小写的问题

这个问题是JSON序列化器的默认大小写策略导致的——不管是Cosmos DB SDK默认用的System.Text.Json,还是你手动配置的Newtonsoft.Json,默认都会对字典键做大小写转换(比如转驼峰式),导致你输入的键格式被修改。

下面分两种常用序列化场景给出解决方案:

方案1:使用System.Text.Json(.NET Core 7.0默认)

配置CosmosClient的序列化选项,明确指定保留字典键的原始大小写:

var cosmosClientOptions = new CosmosClientOptions
{
    SerializerOptions = new CosmosSerializationOptions
    {
        DictionaryKeyPolicy = CosmosDictionaryKeyPolicy.Default, // 保留字典键原始大小写
        PropertyNamingPolicy = null // 可选:如果需要实体类属性名也不转换,加上这行
    }
};

var cosmosClient = new CosmosClient(你的连接字符串, cosmosClientOptions);

CosmosDictionaryKeyPolicy.Default会直接使用字典键的原始字符串,不做任何大小写转换;如果只关心字典键,也可以只设置这一项,不用管PropertyNamingPolicy。

方案2:使用Newtonsoft.Json(替换默认序列化器的情况)

如果你的项目用Newtonsoft.Json替代了默认的System.Text.Json,需要调整序列化配置:

var cosmosClientOptions = new CosmosClientOptions
{
    Serializer = new NewtonsoftJsonCosmosSerializer(new JsonSerializerSettings
    {
        DictionaryKeyHandling = DictionaryKeyHandling.Default,
        ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = null // 禁用属性名的大小写转换策略
        }
    })
};

var cosmosClient = new CosmosClient(你的连接字符串, cosmosClientOptions);

DictionaryKeyHandling.Default会让Newtonsoft.Json保留字典键的原始大小写,NamingStrategy = null则确保实体类的属性名也不会被转换。

验证测试

可以用你提到的示例数据测试:

var testData = new 
{
    DataDict = new Dictionary<string, string>
    {
        { "TEst", "TEST" },
        { "TEST", "TEST" }
    }
};

await container.CreateItemAsync(testData);

查看Cosmos DB中的文档,就能看到TEst和TEST这两个键完全保留了输入时的大小写格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:42:05