【问题标题】:C# and Azure CosmosDB REST API: how to execute stored procedure using HTTPClient.PostAsync?C# 和 Azure CosmosDB REST API:如何使用 HTTPClient.PostAsync 执行存储过程?
【发布时间】:2020-11-26 16:29:22
【问题描述】:

我正在尝试使用 Azure CosmosDB REST API 执行存储过程。根据this document,我需要传递一个包含存储过程输入参数的“数组”。

就我而言,我需要传递一个参数,它是一个对象。我已经序列化了对象,但我不知道如何将它作为 HTTPContent 传递给 PostAsync 方法。为了创建 HTTPContent,我应该使用什么类型的 HTTPContent 以及应该将对象转换为什么类型?

当我使用 Postman 执行此 SP 时,我的请求正文如下所示:

["{\r\n\"id\" : \"someid\",\r\n\"data\": \"somedata\"\r\n}"]

所以我只需要从 JSON 构造这种类型的主体,并在 C# 中将其作为 HTTPContent 传递。

从提供的示例中,我可以得出结论,它是字符串数组。所以我需要序列化我的 JSON,将其添加到数组中,然后将其转换为 HTTPContent。如果是“StringContent”,我应该如何将字符串数组转换为字符串?这不起作用:

string s = "[\"" + serialisedJson + "\"]";
HttpContent c = new StringContent(s, Encoding.UTF8, "application/json");

我收到来自 SP 的 JSON 解析错误。

【问题讨论】:

    标签: azure rest azure-cosmosdb


    【解决方案1】:

    你应该使用StringContent,类似这样:

    client.DefaultRequestHeaders.Add("x-ms-documentdb-partitionkey", "[\"PartitionKey\"]");
    HttpContent content = new StringContent("[{\r\n\"id\" : \"someid\",\r\n\"data\": \"somedata\"\r\n}]", Encoding.UTF8,"application/json");
    HttpResponseMessage response = await client.PostAsync(new Uri(baseUri, resourceLink),content);
    

    【讨论】:

    • 是的,我已经尝试过了,但请求响应错误,因为 SP 无法解析它得到的 JSON。此特定字符串导致“JSON.parse 错误:位置:2 处的字符无效”。因此问题。
    【解决方案2】:

    事实证明,一直以来的答案都是here:CosmosDB API 需要特定的 Content-Type,显然存储过程也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多