您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

Azure Functions 绑定表达式模式Azure Functions binding expression patterns

触发器和绑定的最强大功能之一是绑定表达式One of the most powerful features of triggers and bindings is binding expressions. function.json 文件、函数参数和代码中,可以使用表达式解析为各种源的值。In the function.json file and in function parameters and code, you can use expressions that resolve to values from various sources.

大多数表达式的标识方式是将其包装在大括号中。Most expressions are identified by wrapping them in curly braces. 例如,在队列触发器函数中,{queueTrigger} 解析为队列消息文本。For example, in a queue trigger function, {queueTrigger} resolves to the queue message text. 如果 Blob 输出绑定的 path 属性为 container/{queueTrigger},并且函数由队列消息 HelloWorld 触发,则创建名为 HelloWorld 的 Blob。If the path property for a blob output binding is container/{queueTrigger} and the function is triggered by a queue message HelloWorld, a blob named HelloWorld is created.

绑定表达式的类型Types of binding expressions

绑定表达式 - 应用设置Binding expressions - app settings

作为最佳做法,应使用应用设置(而不是配置文件)来管理密钥和连接字符串。As a best practice, secrets and connection strings should be managed using app settings, rather than configuration files. 这会限制对这些密钥的访问,并可在公共源代码管理存储库中安全存储 function.json 等文件。This limits access to these secrets and makes it safe to store files such as function.json in public source control repositories.

应用设置在想要根据环境更改配置时也很有用。App settings are also useful whenever you want to change configuration based on the environment. 例如,在测试环境中,可能想要监视不同的队列或 blob 存储容器。For example, in a test environment, you may want to monitor a different queue or blob storage container.

应用设置绑定表达式的标识方式不同于其他绑定表达式:它们包装在百分比号而不是大括号中。App setting binding expressions are identified differently from other binding expressions: they are wrapped in percent signs rather than curly braces. 例如,如果 Blob 输出绑定路径为 %Environment%/newblob.txtEnvironment 应用设置值为 Development,则会在 Development 容器中创建 Blob。For example if the blob output binding path is %Environment%/newblob.txt and the Environment app setting value is Development, a blob will be created in the Development container.

当函数在本地运行时,应用设置值来自 local.settings.json 文件。When a function is running locally, app setting values come from the local.settings.json file.

请注意,触发器和绑定的 connection 属性是一种特殊情况,该属性会自动将值解析为应用设置(不带百分比号)。Note that the connection property of triggers and bindings is a special case and automatically resolves values as app settings, without percent signs.

以下示例是一个 Azure 队列存储触发器,该触发器使用应用设置 %input-queue-name% 定义要触发的队列。The following example is an Azure Queue Storage trigger that uses an app setting %input-queue-name% to define the queue to trigger on.

{
  "bindings": [
    {
      "name": "order",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "%input-queue-name%",
      "connection": "MY_STORAGE_ACCT_APP_SETTING"
    }
  ]
}

可在类库中使用此相同的方法:You can use the same approach in class libraries:

[FunctionName("QueueTrigger")]
public static void Run(
    [QueueTrigger("%input-queue-name%")]string myQueueItem, 
    ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}

触发器文件名Trigger file name

Blob 触发器的 path 可以是一种模式,用于引用其他绑定和函数代码中的触发 Blob 的名称。The path for a Blob trigger can be a pattern that lets you refer to the name of the triggering blob in other bindings and function code. 该模式还可包含筛选条件,用于指定哪些 Blob 可以触发函数调用。The pattern can also include filtering criteria that specify which blobs can trigger a function invocation.

例如,在以下 Blob 触发器绑定中,path 模式为 sample-images/{filename}(创建名为 filename 的绑定表达式):For example, in the following Blob trigger binding, the path pattern is sample-images/{filename}, which creates a binding expression named filename:

{
  "bindings": [
    {
      "name": "image",
      "type": "blobTrigger",
      "path": "sample-images/{filename}",
      "direction": "in",
      "connection": "MyStorageConnection"
    },
    ...

然后,可以在输出绑定中使用表达式 filename,用于指定所创建的 Blob 的名称:The expression filename can then be used in an output binding to specify the name of the blob being created:

    ...
    {
      "name": "imageSmall",
      "type": "blob",
      "path": "sample-images-sm/{filename}",
      "direction": "out",
      "connection": "MyStorageConnection"
    }
  ],
}

函数代码可以使用 filename 作为参数名称来访问相同的值:Function code has access to this same value by using filename as a parameter name:

// C# example of binding to {filename}
public static void Run(Stream image, string filename, Stream imageSmall, ILogger log)  
{
    log.LogInformation($"Blob trigger processing: {filename}");
    // ...
} 

类库中的特性同样能够使用绑定表达式和模式。The same ability to use binding expressions and patterns applies to attributes in class libraries. 在以下示例中,特性构造函数参数的值与前面 function.json 示例中的 path 值相同:In the following example, the attribute constructor parameters are the same path values as the preceding function.json examples:

[FunctionName("ResizeImage")]
public static void Run(
    [BlobTrigger("sample-images/{filename}")] Stream image,
    [Blob("sample-images-sm/{filename}", FileAccess.Write)] Stream imageSmall,
    string filename,
    ILogger log)
{
    log.LogInformation($"Blob trigger processing: {filename}");
    // ...
}

还可为文件名的某些部分(例如扩展)创建表达式。You can also create expressions for parts of the file name such as the extension. 有关如何在 Blob 路径字符串中使用表达式和模式的详细信息,请参阅存储 Blob 绑定参考For more information on how to use expressions and patterns in the Blob path string, see the Storage blob binding reference.

触发器元数据Trigger metadata

除了触发器提供的数据有效负载(如触发函数的队列消息内容),许多触发器还会提供其他元数据值。In addition to the data payload provided by a trigger (such as the content of the queue message that triggered a function), many triggers provide additional metadata values. 这些值可用作 C# 和 F# 中的输入参数,或用作 JavaScript 中 context.bindings 对象的属性。These values can be used as input parameters in C# and F# or properties on the context.bindings object in JavaScript.

例如,Azure 队列存储触发器支持以下属性:For example, an Azure Queue storage trigger supports the following properties:

  • QueueTrigger - 如果字符串有效,将触发消息内容QueueTrigger - triggering message content if a valid string
  • DequeueCountDequeueCount
  • ExpirationTimeExpirationTime
  • IdId
  • InsertionTimeInsertionTime
  • NextVisibleTimeNextVisibleTime
  • PopReceiptPopReceipt

这些元数据值可在 function.json 文件属性中访问 。These metadata values are accessible in function.json file properties. 例如,假设使用队列触发器,且队列消息中包含要读取的 blob 的名称。For example, suppose you use a queue trigger and the queue message contains the name of a blob you want to read. 在 function.json 文件中 ,可在 blob path 属性中使用 queueTrigger 元数据属性,如下面的示例中所示:In the function.json file, you can use queueTrigger metadata property in the blob path property, as shown in the following example:

  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "queueName": "myqueue-items",
      "connection": "MyStorageConnection",
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "direction": "in",
      "connection": "MyStorageConnection"
    }
  ]

相应参考文章中会详细介绍每种触发器的元数据属性。Details of metadata properties for each trigger are described in the corresponding reference article. 有关示例,请参阅队列触发器元数据For an example, see queue trigger metadata. 在门户“集成” 选项卡的绑定配置区域下方的“文档” 部分中,还提供了文档。Documentation is also available in the Integrate tab of the portal, in the Documentation section below the binding configuration area.

JSON 有效负载JSON payloads

当触发器有效负载为 JSON 时,可以在相同的函数和函数代码中,引用其他绑定的配置中的相应属性。When a trigger payload is JSON, you can refer to its properties in configuration for other bindings in the same function and in function code.

以下示例演示一个接收 JSON 格式 Blob 名称的 Webhook 函数的 function.json 文件:{"BlobName":"HelloWorld.txt"}The following example shows the function.json file for a webhook function that receives a blob name in JSON: {"BlobName":"HelloWorld.txt"}. Blob 输入绑定读取 Blob,HTTP 输出绑定在 HTTP 响应中返回 Blob 内容。A Blob input binding reads the blob, and the HTTP output binding returns the blob contents in the HTTP response. 可以看到,Blob 输入绑定通过直接引用 BlobName 属性来获取 Blob 名称 ("path": "strings/{BlobName}")Notice that the Blob input binding gets the blob name by referring directly to the BlobName property ("path": "strings/{BlobName}")

{
  "bindings": [
    {
      "name": "info",
      "type": "httpTrigger",
      "direction": "in",
      "webHookType": "genericJson"
    },
    {
      "name": "blobContents",
      "type": "blob",
      "direction": "in",
      "path": "strings/{BlobName}",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ]
}

要在 C# 和 F# 中运行此代码,需要使用一个类来定义要反序列化的字段,如以下示例中所示:For this to work in C# and F#, you need a class that defines the fields to be deserialized, as in the following example:

using System.Net;
using Microsoft.Extensions.Logging;

public class BlobInfo
{
    public string BlobName { get; set; }
}
  
public static HttpResponseMessage Run(HttpRequestMessage req, BlobInfo info, string blobContents, ILogger log)
{
    if (blobContents == null) {
        return req.CreateResponse(HttpStatusCode.NotFound);
    } 

    log.LogInformation($"Processing: {info.BlobName}");

    return req.CreateResponse(HttpStatusCode.OK, new {
        data = $"{blobContents}"
    });
}

在 JavaScript 中,会自动执行 JSON 反序列化。In JavaScript, JSON deserialization is automatically performed.

module.exports = function (context, info) {
    if ('BlobName' in info) {
        context.res = {
            body: { 'data': context.bindings.blobContents }
        }
    }
    else {
        context.res = {
            status: 404
        };
    }
    context.done();
}

点表示法Dot notation

如果 JSON 有效负载中的某些属性是包含属性的对象,可以使用点表示法直接引用这些对象。If some of the properties in your JSON payload are objects with properties, you can refer to those directly by using dot notation. 例如,假设 JSON 如下所示:For example, suppose your JSON looks like this:

{
  "BlobName": {
    "FileName":"HelloWorld",
    "Extension":"txt"
  }
}

可以直接以 BlobName.FileName 的形式引用 FileNameYou can refer directly to FileName as BlobName.FileName. 使用此 JSON 格式时,上述示例中的 path 属性如下所示:With this JSON format, here's what the path property in the preceding example would look like:

"path": "strings/{BlobName.FileName}.{BlobName.Extension}",

在 C# 中,需要两个类:In C#, you would need two classes:

public class BlobInfo
{
    public BlobName BlobName { get; set; }
}
public class BlobName
{
    public string FileName { get; set; }
    public string Extension { get; set; }
}

创建 GUIDCreate GUIDs

{rand-guid} 绑定表达式用于创建 GUID。The {rand-guid} binding expression creates a GUID. function.json 文件中的以下 Blob 路径创建名称类似于 50710cb5-84b9-4d87-9d83-a03d6976a682.txt 的 Blob。The following blob path in a function.json file creates a blob with a name like 50710cb5-84b9-4d87-9d83-a03d6976a682.txt.

{
  "type": "blob",
  "name": "blobOutput",
  "direction": "out",
  "path": "my-output-container/{rand-guid}"
}

当前时间Current time

绑定表达式 DateTime 解析为 DateTime.UtcNowThe binding expression DateTime resolves to DateTime.UtcNow. function.json 文件中的以下 Blob 路径创建名称类似于 2018-02-16T17-59-55Z.txt 的 Blob。The following blob path in a function.json file creates a blob with a name like 2018-02-16T17-59-55Z.txt.

{
  "type": "blob",
  "name": "blobOutput",
  "direction": "out",
  "path": "my-output-container/{DateTime}"
}

在运行时绑定Binding at runtime

在 C# 和其他 .NET 语言中,可以使用命令性绑定模式,而不是 function.json 和特性中的声明式绑定。In C# and other .NET languages, you can use an imperative binding pattern, as opposed to the declarative bindings in function.json and attributes. 当绑定参数需要在运行时(而非在设计时)计算时,命令性绑定很有用。Imperative binding is useful when binding parameters need to be computed at runtime rather than design time. 若要了解详细信息,请参阅 C# 开发人员参考C# 脚本开发人员参考To learn more, see the C# developer reference or the C# script developer reference.

后续步骤Next steps