使用动态 DocumentId 从 Azure Functions 访问 DocumentDb

Accessing DocumentDb from Azure Functions with dynamic DocumentId

这是我的 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}");
}

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

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

No binding parameter exists for 'documentId'.

我的post数据是:

{
    "documentId": "002"
}

如何将 DocumentId 发送到我的 Azure 函数并从 DocumentDb 获取关联项?

一个解决方案可能是自己解析 post 数据。像这样:

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,则可以使用 DocumentDb 的 .NET Client SDK 或 REST API,就像在控制台应用程序中一样。

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

#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"
    }
  ]
}