c# - ApiHubFile Azure Function 绑定(bind)的动态输出文件名(一个驱动器、投递箱等)

标签 c# azure azure-functions

我有一个带有计时器触发器的Azure函数,然后我想生成一个具有动态(在运行时定义)名称和内容的文件并将其保存到例如OneDrive。

我的函数代码:

public static void Run(TimerInfo myTimer, out string filename, out string content)
{
    filename = $"{DateTime.Now}.txt";
    content = $"Generated at {DateTime.Now} by Azure Functions";    
}

function.json:

{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 */5 * * * *"
    },
    {
      "type": "apiHubFile",
      "name": "content",
      "path": "{filename}",
      "connection": "onedrive_ONEDRIVE",
      "direction": "out"
    }
  ],
  "disabled": false
}

但这失败了,

Error indexing method 'Functions.TimerTriggerCSharp1'. Microsoft.Azure.WebJobs.Host: 
Cannot bind parameter 'filename' to type String&. Make sure the parameter Type 
is supported by the binding. If you're using binding extensions 
(e.g. ServiceBus, Timers, etc.) make sure you've called the registration method 
for the extension(s) in your startup code (e.g. config.UseServiceBus(), 
config.UseTimers(), etc.).

最佳答案

以下是您可以执行的操作:

#r "Microsoft.Azure.WebJobs.Extensions.ApiHub"

using System;
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host.Bindings.Runtime;

public static async Task Run(TimerInfo myTimer, TraceWriter log, Binder binder)
{
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");    

    var fileName = "mypath/" + DateTime.Now.ToString("yyyy-MM-ddThh-mm-ss") + ".txt";

    var attributes = new Attribute[]
    {    
        new ApiHubFileAttribute("onedrive_ONEDRIVE", fileName, FileAccess.Write)
    };


    var writer = await binder.BindAsync<TextWriter>(attributes);
    var content = $"Generated at {DateTime.Now} by Azure Functions"; 

    writer.Write(content);
}

以及 function.json 文件:

    {
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "10 * * * * *"
    },
    {
      "type": "apiHubFile",
      "name": "outputFile",
      "connection": "onedrive_ONEDRIVE",
      "direction": "out"
    }
  ],
  "disabled": false
}

您实际上不应该在 function.json 中需要 apiHubFile 声明,但由于我今天注意到的一个错误,它应该仍然存在。我们将修复该错误。

关于c# - ApiHubFile Azure Function 绑定(bind)的动态输出文件名(一个驱动器、投递箱等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348985/

相关文章:

c# - 这个 "Lambda Expression"是做什么的?

c# - 将 double 值转换为二进制值

c# - 为什么 Task<T> monad 中不包含 CancellationToken?

azure - 在 Azure Shell 文本编辑器中创建的文件位于 Azure 门户中的什么位置?

c# - Azure key 保管库有哪些优势?

azure - 如何为 Azure Functions 和 Playwright 创建多级 docker 文件?

c# - Azure Function 对 Newtonsoft 11.0.2 和 Docker 容器的硬依赖

C# Selenium RC - 如何测试 jQuery 按钮点击?

azure - 如何动态更新 Azure APIM 中的后端/出站 URL

C# Azure 函数 : Can't use CloudQueue type as output binding