2017-03-16 45 views
2

这里访问DocumentDb是我function.json:从Azure的功能与动态DocumentId

{ 
    "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在config中的固定值。

但是,当我想用​​一个动态的文档ID和使用{documentId},我得到这个错误:

No binding parameter exists for 'documentId'. 

后数据是:

{ 
    "documentId": "002" 
} 

哪有我发送DocumentId到我的Azure函数并从DocumentDb获取相关项目?

回答

4

要在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" 
    } 
    ] 
} 
+0

我测试了一个类似于此的代码(输入有效载荷,poco对象,...)但出现了一些错误。我会再次测试它,如果这个工作有效,现在让你。使用这个示例:https://github.com/Azure/azure-webjobs-sdk-script/blob/dev/sample/WebHook-Generic-CSharp/run.csx –

+0

非常感谢,这工作完美。使用动态对象引发的错误,但使用POCO的工作,也添加输入参数function.json使这项工作(我认为我上次犯了一些错误,这一次仔细添加) –

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,您可以使用DocumentDb或.NET客户端SDK的REST API就像你会从一个控制台应用程序。

+0

谢谢。我知道这个解决方案,但这看起来很难。任何其他方式来绑定documentId? –