azure - 如何使用 Binder 在 C# 函数中执行动态绑定(bind)?

标签 azure azure-functions

我需要绑定(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/

相关文章:

java - Azure Java函数-502-错误网关

node.js - 多部分/表单数据到 azure blob

azure - 如何查找 Azure Function App IP 进行白名单

azure - Windows Azure 上的 32 位旧版 COM DLL

azure - 使用 TFS Azure 进行临时异地部署?

sql-server - 如何从 Azure SQL 调用 Webservice/CLR 函数

azure - 如何重用 QueueClient 实例从 Azure Function 发送响应消息?

entity-framework - 使用混合连接管理器创建 Azure 混合连接

sql-server - 使用 Docker 连接的 SQL Server 物理文件夹

azure - 如何将 CloudStorageAccount 输入绑定(bind)到 Azure Function?