繁体   English   中英

使用动态DocumentId从Azure函数访问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}");
}

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

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

No binding parameter exists for 'documentId'.

我的帖子数据是:

{
    "documentId": "002"
}

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

要在C#绑定表达式中使用自定义参数,必须在触发器输入绑定到的类型上定义这些属性。 由于您要从输入有效内容绑定到documentId ,因此我们定义了具有相应DocumentId属性的Input 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"
    }
  ]
}

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM