响应状态码不表示成功:BadRequest(400);子状态:0 表示基本 CosmosDb 插入

问题描述 投票:0回答:1

我的对象模型:

public class PhoneBook
{
    public string Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

我的容器创建:

db.CreateContainerIfNotExistsAsync("phoneBooks", "/id")

我的插入命令:

PhoneBook pb = new() { Id = Guid.NewGuid().ToString(), Name = "hello world };

db.GetContainer("phoneBooks").CreateItemAsync(pb, new PartitionKey(pb.Id));

知道我哪里出错了吗?

我还尝试使用“/Id”作为分区键,因为我认为它必须区分大小写。然而,却没有一丝喜悦。使用数据浏览器,即使我将属性命名为“id”并且分区键为“/Id”,我也可以很好地添加内容。这是我手动添加的项目

{ “id”:“4faebd8b-717a-4692-ae00-74aa209d706f”, “名称”:“你好世界”}

c# azure-cosmosdb
1个回答
0
投票

响应状态码不表示成功:BadRequest(400);子状态:0

谢谢你的建议,大卫。它运行良好,通过在

Id
属性中提及 [JsonProperty("id")],数据已成功插入到 Azure Cosmos DB 容器中,如下面的代码所示。

public class PhoneBook
{
    [JsonProperty("id")]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public CosmosDbService(string endpointUri, string primaryKey, string databaseId, string containerId)
{
    CosmosClientOptions clientOptions = new CosmosClientOptions
    {
        ConnectionMode = ConnectionMode.Direct,
        MaxRetryAttemptsOnRateLimitedRequests = 5,
        MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(30)
    };

    _cosmosClient = new CosmosClient(endpointUri, primaryKey, clientOptions);

    _database = _cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId).GetAwaiter().GetResult().Database;

    _container = _database.CreateContainerIfNotExistsAsync(containerId, "/id").GetAwaiter().GetResult().Container;
}

public static async Task Main(string[] args)
{
    string endpointUri = "*****";
    string primaryKey = "*****";
    string databaseId = "db1";
    string containerId = "phoneBooks";

    CosmosDbService cosmosDbService = new CosmosDbService(endpointUri, primaryKey, databaseId, containerId);

    PhoneBook pb = new PhoneBook
    {
        Id = Guid.NewGuid().ToString(),
        Name = "hello world",
        Description = "Sample description"
    };

    await cosmosDbService.CreatePhoneBookItemAsync(pb);
}

输出:

{
    "id": "69daea1c-fd73-4c27-89b0-50428f27ef89",
    "Name": "hello world",
    "Description": "Sample description"
}

enter image description here

  • 通过此链接了解有关该错误的更多信息。
© www.soinside.com 2019 - 2024. All rights reserved.