使用CosmosDB文档输出

时间:2017-10-04 17:15:06

标签: azure azure-functions azure-cosmosdb

我想创建一个Azure函数,该函数将JSON正文传递给它并将此文档插入Azure COSMOSDB实例。

为此,我在Azure Functions Portal中创建了此功能: Azure Function configuration

并实现如下功能:

#r "Newtonsoft.Json"
using Newtonsoft.Json.Linq;

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, object outputDocument)
{
    var requestContent = await req.Content.ReadAsStringAsync();
    log.Verbose($@"Received request:\n{requestContent}");

    var newDoc = JObject.Parse(requestContent);
    newDoc["Id"] = Guid.NewGuid().ToString();
    newDoc["shardKey"] = newDoc.Value<string>(@"Id").Substring(8);

    outputDocument = newDoc;

    return req.CreateResponse(System.Net.HttpStatusCode.Created);
}

在门户网站中,我提供了一个简单的示例文档:

{
  "prop1": 2,
  "prop2": "2017-02-20",
}

然后点击“运行”

我马上遇见了 portal IDE error

作为门户网站IDE中的叠加层和

{
  "id": "145ee924-f824-4064-8364-f96dc12ab138",
  "requestId": "5a27c287-2c91-40f5-be52-6a79c7c86bc2",
  "statusCode": 500,
  "errorCode": 0,
  "message": "'UploadDocumentToCosmos' can't be invoked from Azure WebJobs SDK. Is it missing Azure WebJobs SDK attributes?"
}

在日志区域。

我似乎没有办法解决这个问题,但我确实觉得我做的一切都是正确的。

如何将JSON对象作为HTTP请求添加到Azure函数,并将所述对象插入/插入Azure Cosmos数据库实例,我需要做什么?

2 个答案:

答案 0 :(得分:1)

对于异步功能,您应该使用IAsyncCollector

public static async Task<HttpResponseMessage> Run(
    HttpRequestMessage req, TraceWriter log, 
    IAsyncCollector<object> outputDocuments)
{
    ...
    await outputDocuments.AddAsync(newDoc);
}

答案 1 :(得分:-2)

您可以尝试将out添加到dynamic outputDocument吗?

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, out dynamic outputDocument)