【发布时间】:2016-10-04 14:49:56
【问题描述】:
我需要绑定到输出 blob,但 blob 路径需要在我的函数中动态计算。我该怎么做?
【问题讨论】:
标签: azure azure-functions
我需要绑定到输出 blob,但 blob 路径需要在我的函数中动态计算。我该怎么做?
【问题讨论】:
标签: azure azure-functions
Binder 是一种高级绑定技术,它允许您在代码中强制 执行绑定,而不是通过function.json 元数据文件声明式。如果绑定路径或其他输入的计算需要在函数运行时发生,您可能需要执行此操作。请注意,当使用 Binder 参数时,您不应在 function.json 中包含该参数的相应条目。
在下面的示例中,我们动态绑定到 blob 输出。如您所见,因为您在代码中声明了绑定,所以您的路径信息可以以您希望的任何方式计算。请注意,您也可以绑定到任何其他原始绑定属性(例如QueueAttribute/EventHubAttribute/ServiceBusAttribute/等)。您也可以反复执行此操作以绑定多次。
请注意,传递给BindAsync(在本例中为TextWriter)的类型参数必须是目标绑定支持的类型。
using System;
using System.Net;
using Microsoft.Azure.WebJobs;
public static async Task<HttpResponseMessage> Run(
HttpRequestMessage req, Binder binder, TraceWriter log)
{
log.Verbose($"C# HTTP function processed RequestUri={req.RequestUri}");
// determine the path at runtime in any way you choose
string path = "samples-output/path";
using (var writer = await binder.BindAsync<TextWriter>(new BlobAttribute(path)))
{
writer.Write("Hello World!!");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
这里是对应的元数据:
{
"bindings": [
{
"name": "req",
"type": "httpTrigger",
"direction": "in"
},
{
"name": "res",
"type": "http",
"direction": "out"
}
]
}
有些绑定重载采用 array 属性。在您需要控制目标存储帐户的情况下,您可以传入一组属性,从绑定类型属性(例如BlobAttribute)开始,并包括一个指向要使用的帐户的StorageAccountAttribute 实例。例如:
var attributes = new Attribute[]
{
new BlobAttribute(path),
new StorageAccountAttribute("MyStorageAccount")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
writer.Write("Hello World!");
}
【讨论】:
已将来自其他帖子的所有信息与 cmets 合并,并创建了一个 blog post,以演示如何在现实世界场景中使用 Binder。感谢@mathewc,这成为可能。
【讨论】:
Binder 还是有更惯用的方式来完成条件绑定属性等?