在ASP.NET Core 3.1中将JsonElement放入CosmosDB

问题描述

您会认为这很容易,只要摆脱日志,但我很沮丧。我有一个ASP.NET 3.1核心Web API(使用System.Text.Json):

[HttpPost]
public async Task<ActionResult> CreateAsync(JsonElement dzc)

依次调用服务:

public async Task AddItemAsync(JsonElement dzc)
{
    var id = dzc.GetProperty("id").GetString();  // these are both valid
    var userid = dzc.GetProperty("userid").GetString();

    await this._container.CreateItemAsync<JsonElement>(dzc,new PartitionKey(userid));
}

这将导致:消息:{“错误”:[“输入内容无效,因为必需的属性-'id;'-丢失”]}

或者如果我收到原始文本:

public async Task AddItemAsync(JsonElement dzc)
{
    var id = dzc.GetProperty("id").GetString();  // these are all valid
    var userid = dzc.GetProperty("userid").GetString();
    var raw = dzc.GetRawText();

    await this._container.CreateItemAsync<string>(raw,new PartitionKey(userid));
}

原始是:

{
    "id": "foozy","userid": "foozy","name": "Jayb","fc": {
        "type": "FeatureCollection","features": [
            {
                "type": "Feature","properties": {
                    "capacity": "10",},"geometry": {
                    "type": "Point","coordinates": [
                        -71.073283,42.417500
                    ]
                }
            }
        ]
    }
}

这将导致:消息:{“错误”:[“指定的输入之一无效”]}

我真正想做的只是将一些Json从API直接铲入CosmosDB,而无需使用C#类。什么是魔咒?

解决方法

简短答案...您无法通过CreateItemAsyncdocumentation明确指出需要一个id属性,根据定义,该属性在JsonElementstring上均不存在。

一个更好的选择是使用CreateItemStreamAsync,它允许您直接传递原始流,并根据example in the documentation似乎绕过了ID属性要求。

using (Response response = await this.Container.CreateItemStreamAsync(partitionKey: new PartitionKey("streamPartitionKey"),streamPayload: stream))
{
    using (Stream responseStream = await response.ContentStream)
    {
        //Read or do other operations with the stream
        using (StreamReader streamReader = new StreamReader(responseStream))
        {
            string responseContentAsString = await streamReader.ReadToEndAsync();
        }
    }
}
,

感谢David L,您的建议非常有效!这就是我最终得到的:

public async Task AddItemAsync(JsonElement dzc)
{
    var id = dzc.GetProperty("id").GetString();
    var userid = dzc.GetProperty("userid").GetString();

    var raw = dzc.GetRawText();
    byte[] bytes = Encoding.UTF8.GetBytes(raw);
    using (var stream = new MemoryStream(bytes))
    {
        await this._container.CreateItemStreamAsync(stream,new PartitionKey(userid));
    }
}

我很好奇是否可以避免复制。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...