我有一个带有计时器触发器的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.).
答案 0 :(得分:4)
以下是如何做到这一点:
#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
}
您不应该在apiHubFile
中真正需要function.json
声明,但由于我今天发现的错误,它应该仍然在那里。我们将解决这个问题。
答案 1 :(得分:2)
要在功能执行期间完全控制输出的名称和路径,您需要使用imperative binding
例如:function.json
{
"type": "blob",
"name": "outputBinder",
"path": "export/test",
"connection": "AzureWebJobsStorage",
"direction": "out"
},
功能:
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, IBinder outputBinder)
{
var attribute new BlobAttribute($"{some dynamic path}/{some dynamic filename}", FileAccess.Write);
using (var stream = await outputBinder.BindAsync<Stream>(attribute))
{
// do whatever you want with this stream here...
}
}