使用动态DocumentId从Azure Functions访问DocumentDb

时间:2017-03-16 09:03:55

标签: c# azure azure-cosmosdb azure-functions

这是我的 function.json:

{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "webHookType": "genericJson",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "MyDb",
      "collectionName": "MyCol",
      "partitionKey": "main",
      "id": "{documentId}",
      "connection": "MyDocDbConnStr",
      "direction": "in"
    }
  ],
  "disabled": false
}

这是我的 run.csx:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log, dynamic inputDocument)
{

    return req.CreateResponse(HttpStatusCode.OK, $"doc title is {inputDocument.title}");
}

如果我在config中为我的文档ID定义一个固定值,那么一切正常。

但是当我想使用动态文档ID并使用 {documentId} 时,我收到此错误:

No binding parameter exists for 'documentId'.

我的发布数据是:

{
    "documentId": "002"
}

如何将 DocumentId 发送到我的Azure功能并从DocumentDb获取相关项目?

2 个答案:

答案 0 :(得分:4)

要在C#绑定表达式中使用自定义参数,必须在触发器输入绑定的类型上定义这些属性。由于您希望从输入有效内容绑定到documentId,因此我们使用相应的Input属性定义DocumentId POCO。这是一个工作样本:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public class Input
{
    public string DocumentId { get; set; }
}

public static HttpResponseMessage Run(Input input, 
              HttpRequestMessage req, dynamic document, TraceWriter log)
{
    if (document != null)
    {
        log.Info($"DocumentId: {document.text}");
        return req.CreateResponse(HttpStatusCode.OK);
    }
    else
    {
        return req.CreateResponse(HttpStatusCode.NotFound);
    }
}

这是相应的function.json:

{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "webHookType": "genericJson",
      "name": "input"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "documentDB",
      "name": "document",
      "databaseName": "ItemDb",
      "collectionName": "ItemCollection",
      "id": "{documentId}",
      "connection": "test_DOCUMENTDB",
      "direction": "in"
    }
  ]
}

答案 1 :(得分:1)

解决方案可能是自己解析帖子数据。像这样:

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    string jsonContent = await req.Content.ReadAsStringAsync();
    dynamic data = JsonConvert.DeserializeObject(jsonContent);
    return req.CreateResponse(HttpStatusCode.OK, $"doc title is {data.documentId}");
}

然后,如果您拥有documentId,则可以像使用Console App一样使用.NET Client SDK for DocumentDb或REST API。