使用HTTP触发器读取和写入Blob的Azure函数

时间:2020-07-09 23:00:23

标签: c# azure visual-studio-code azure-functions azure-storage-blobs

让我开始说我绝不是C#开发人员,因此我对新手问题和后续回答深表歉意。

我试图编写一个Azure函数,该函数一旦被HTTP触发器调用,将转到一个Blob,读取数据,转换数据,然后写入另一个Blob存储。忽略转换层,我只是尝试从blob读取并上传到单独的blob。以下是我目前拥有的代码:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;

public static void Run(HttpRequest req, Stream inputBlob, Stream outputBlob, ILogger log)
{
    StreamReader reader = new StreamReader(inputBlob);
    string  text = reader.ReadToEnd();
    await outputBlob.UploadTextAsync(text)
}

这是我的绑定物:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "name": "inputBlob",
      "direction": "in",
      "type": "blob",
      "path": "path/to/file",
      "connection": "*********_STORAGE"
    },
    {
      "name": "outputBlob",
      "direction": "out",
      "type": "blob",
      "path": "path/to/file",
      "connection": "*********_STORAGE"
    }
  ]
}

当我在Azure Function UI中对其进行测试时,状态为500-Internal Server Error。如果我在经典查看器中对其进行测试,则日志会给我以下响应:“该请求无权执行此操作”。我正在使用Azure UI开发无法在我的计算机上设置的VSCode Azure Function核心工具。

有人可以提供一些关于我要去哪里的信息吗?任何代码片段/示例都将不胜感激,但是我已经对所有StackOverflow进行了精练,并且未能成功运行我发现的任何代码片段。

1 个答案:

答案 0 :(得分:0)

对于此问题,我将在您的代码中对其进行测试。请参考以下解决方案:

1。。在UploadTextAsync()中不存在方法Stream outputBlob。因此,请使用下面的代码将文本从inputBlob写入outputBlob

byte[] bytes = Encoding.ASCII.GetBytes(text);
await outputBlob.WriteAsync(bytes);

还提供以下所有我的功能代码,供您参考:

enter image description here

2。。除了编辑您的函数代码外,还请检查您的function.json与我的绑定是否相同(test中的path是容器名称在存储中)。

enter image description here

storageCon是应在应用程序设置中添加的值(连接字符串)的名称。 我们无法将连接字符串硬编码为function.json

enter image description here

3。。运行该功能,它将读取inputBlob文件并将其写入outputBlob文件。

希望有帮助〜