c# - 在异步方法中绑定(bind)到输出 Blob 时,将 Blob 绑定(bind)到 IAsyncCollector 时出错

标签 c# azure asynchronous azure-blob-storage azure-functions

我正在尝试在这篇文章之后的异步方法中绑定(bind)到 blob 输出: How can I bind output values to my async Azure Function?

我有多个输出绑定(bind),因此仅返回不是一个选项

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, IAsyncCollector<string> collection, TraceWriter log)
{
    if (req.Method == HttpMethod.Post) 
    {
        string jsonContent = await req.Content.ReadAsStringAsync();

        // Save to blob 
        await collection.AddAsync(jsonContent);

        return req.CreateResponse(HttpStatusCode.OK);
    }
    else 
    {
        return req.CreateResponse(HttpStatusCode.BadRequest);

    }
}

我对 blob 的绑定(bind)是:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "blob",
      "name": "collection",
      "path": "testdata/{rand-guid}.txt",
      "connection": "test_STORAGE",
      "direction": "out"
    }
  ],
  "disabled": false
}

但每当我这样做时,我都会得到以下信息:

Error: Function ($WebHook) Error: Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.WebHook'. Microsoft.Azure.WebJobs.Host: Can't bind Blob to type 'Microsoft.Azure.WebJobs.IAsyncCollector`1[System.String]'

最佳答案

Blob 输出绑定(bind)不支持收集器,请参阅此 issue .

对于可变数量的输出 blob(在您的情况下为 0 或 1,但可以是任意),您必须使用命令式绑定(bind)。从 function.json 中删除 collection 绑定(bind),然后执行以下操作:

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, Binder binder)
{
    if (req.Method == HttpMethod.Post) 
    {
        string jsonContent = await req.Content.ReadAsStringAsync();

        var attributes = new Attribute[]
        {    
            new BlobAttribute("testdata/{rand-guid}.txt"),
            new StorageAccountAttribute("test_STORAGE")
        };

        using (var writer = await binder.BindAsync<TextWriter>(attributes))
        {
            writer.Write(jsonContent);
        }

        return req.CreateResponse(HttpStatusCode.OK);
    }
    else 
    {
        return req.CreateResponse(HttpStatusCode.BadRequest);    
    }
}

关于c# - 在异步方法中绑定(bind)到输出 Blob 时,将 Blob 绑定(bind)到 IAsyncCollector 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44670977/

相关文章:

c# - 在 C# 2.0 中创建向导的最佳方法是什么?

c# - 使用 Moq 模拟存储库

c# - 通过 winform 循环切换

Azure Pipelines 自动重试任务

node.js - 为什么对 Redis 使用异步客户端有意义?

c# - 使用 System.Text.Json 进行自定义反序列化

azure - 使用 Azure 自动化帐户,将文件从一个文件共享跨存储复制到另一个文件共享

Azure 容器注册表 - 删除除 2 之外的所有镜像

java - 用于异步调用的 Apache Camel

javascript - Ajax - 所有请求均已完成/完成