c# - 使用动态 DocumentId 从 Azure Functions 访问 DocumentDb

标签 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}");
}

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

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

No binding parameter exists for 'documentId'.

我的帖子数据是:

{
    "documentId": "002"
}

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

最佳答案

要在 C# 绑定(bind)表达式中使用自定义参数,必须在触发器输入绑定(bind)到的类型上定义这些属性。由于您想要从输入有效负载绑定(bind)到 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"
    }
  ]
}

关于c# - 使用动态 DocumentId 从 Azure Functions 访问 DocumentDb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42829465/

相关文章:

c# - 在单个查询中从 CosmosDb 中获取多种类型的实体

node.js - Azure Function Runtime 版本 : 2. 0.11888.0(测试版)变得无法连接到 cosmosDB

java - 如何使用 azure-documentdb 在 java 代码中配置数据库级别的吞吐量

C# 线程和内存泄漏

security - Sitecore 8.1 : azure website forbidden by its access permissions 127. 0.0.1

powershell - 匿名列出公共(public)容器中的 Azure 存储 blob

node.js - 从 OSX 命令行发布 azure 网站?

c# - 使用 MVC.UrlHelper 从 MVC View 中解析 WebApi 操作 Url

c# - 使用执行阅读器从 SQL 获取返回值

c# - ZedGraph 如何使用 XAxis.Type = AxisType.Text 创建经典折线图