Azure 函数 blob 绑定

Azure Function blob binding

如果不在 C# 实现(非 CSX)中使用 [BlobAttribute],我无法将 blob 类型的输入参数绑定到任一 string/TextReader。

我得到的错误是:

Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.Harvester'. 
Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'configReader' to type 
TextReader. 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.).

function.config:

"bindings": [
    {
      "type": "timerTrigger",
      "schedule": "0 */5 * * * *",
      "useMonitor": true,
      "runOnStartup": false,
      "direction": "in",
      "name": "myTimer"
    },
    {
      "type": "blob",
      "name": "configReader",
      "path": "secured/app.config.json",
      "connection": "XXX",
      "direction": "in"
    }
  ],

函数签名(不绑定 configReader):

[FunctionName("Harvester")]
 public static async Task Run(
   [TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
   TraceWriter log,
   TextReader configReader)

虽然这会起作用(绑定 configReader:

[FunctionName("Harvester")]
 public static async Task Run(
   [TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
   TraceWriter log,
   [Blob("secured/app.config.json", FileAccess.Read)]TextReader configReader)

关于如何在不指定 BlobAttribute 中的 blob 路径的情况下使其工作的任何想法。理想情况下,我会将 Blob 配置保留在代码之外,这样我的函数将变得更加可移植。

问题出在 function.json

中支持新 属性 (configurationSource) 的最新运行时

这告诉运行时使用 config(即 function.json)或 C# 属性进行函数配置。

基本上允许您像这样定义函数

现在您可以将函数定义为

[FunctionName("Harvester")]
public static async Task Run(
    [TimerTrigger]TimerInfo myTimer,
    TraceWriter log,
    TextReader configReader)
{
}

连同看起来像这样的 function.json

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "config",
  "bindings": [
    {
      "type": "timerTrigger",
      "schedule": "0 */5 * * * *",
      "useMonitor": true,
      "runOnStartup": false,
      "direction": "in",
      "name": "myTimer"
    },
    {
      "type": "blob",
      "name": "configReader",
      "path": "secured/app.config.json",
      "connection": "XXX",
      "direction": "in"
    }
  ],
  "disabled": false,
  "scriptFile": "...",
  "entryPoint": "..."
}

或者像这样

[FunctionName("Harvester")]
public static async Task Run(
    [TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
    TraceWriter log,
    [Blob("secured/app.config.json", FileAccess.Read)]TextReader configReader)
{
}

使用像这样更简单的配置

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "timerTrigger",
      "name": "myTimer"
    },
  ],
  "scriptFile": "...",
  "entryPoint": "..."
}

注意两个示例中 configurationSource 的值。

Visual Studio 2017 的工具默认执行后者。如果您想更改 function.json 以包含所有配置并更改 configurationSource,则需要将文件包含在项目中并将其标记为始终复制。此 GIF 展示了如何做到这一点。