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

Cosmos DB Patch操作因纯数字属性名触发连接强制关闭异常

Azure Cosmos DB Patch操作纯数字长属性名报错解决方案

问题描述

使用Azure Cosmos DB的Patch操作创建或更新文档属性时,若属性名为12位及以上纯数字,会抛出以下异常:

SocketException: An existing connection was forcibly closed by the remote host.

示例代码:

var _endpointUri = "https://localhost:8081/";
var _primaryKey = "primary key";

using CosmosClient client = new CosmosClient(_endpointUri, _primaryKey);
var database = client.GetDatabase("Orders");
var container = database.GetContainer("Batches");

List<PatchOperation> operations = new()
{
    PatchOperation.Set($"/batches/111122223333", DateTime.Now),
};

ItemResponse<BatchIndexDocument> r = await container.PatchItemAsync<BatchIndexDocument>(
    id: "10001",
    partitionKey: new PartitionKey("10001"),
    patchOperations: operations,
    requestOptions: opt
);

将属性名替换为字母后,操作可正常完成无报错。

原因分析

Cosmos DB的JSON Patch路径解析逻辑中,纯数字的路径段会默认被当作数组索引处理。当数字长度较长时,内部解析过程中会出现数值溢出或逻辑错误,导致连接被远端强制关闭。而若batches是对象而非数组,这种解析逻辑就会触发异常。

解决方案

方案1:用引号包裹纯数字属性名

在Patch路径中,将纯数字属性名用单引号包裹,明确告知Cosmos DB这是对象的属性而非数组索引。

修改后的代码:

List<PatchOperation> operations = new()
{
    PatchOperation.Set($"/batches/'111122223333'", DateTime.Now),
};

方案2:修改属性名格式

避免直接使用纯数字作为属性名,可添加前缀、后缀或混合字母,比如:

List<PatchOperation> operations = new()
{
    PatchOperation.Set($"/batches/batch_111122223333", DateTime.Now),
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:54:56