我需要绑定(bind)到输出 blob,但需要在函数中动态计算 blob 路径。我该怎么做?
最佳答案
Binder
是一种高级绑定(bind)技术,允许您在代码中命令式执行绑定(bind),而不是通过函数声明式执行绑定(bind).json
元数据文件。如果需要在函数运行时计算绑定(bind)路径或其他输入,您可能需要执行此操作。请注意,使用 Binder
参数时,您不应在 function.json
中包含该参数的相应条目。
在下面的示例中,我们动态绑定(bind)到 blob 输出。如您所见,由于您在代码中声明绑定(bind),因此可以按照您希望的任何方式计算路径信息。请注意,您也可以绑定(bind)到任何其他原始绑定(bind)属性(例如QueueAttribute
/EventHubAttribute
/ServiceBusAttribute
/等)您还可以迭代地执行此操作以绑定(bind)多次。
请注意,传递给 BindAsync
的类型参数(在本例中为 TextWriter
)必须是目标绑定(bind)支持的类型。
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"
}
]
}
有一些绑定(bind)重载采用属性的数组。如果您需要控制目标存储帐户,则可以传入属性集合,从绑定(bind)类型属性(例如 BlobAttribute
)开始,并包含一个 StorageAccountAttribute
实例指向到要使用的帐户。例如:
var attributes = new Attribute[]
{
new BlobAttribute(path),
new StorageAccountAttribute("MyStorageAccount")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
writer.Write("Hello World!");
}
关于azure - 如何使用 Binder 在 C# 函数中执行动态绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39855409/