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.

下列範例是使用應用程式設定 %input-queue-name% 來定義要觸發之佇列的 Azure 佇列儲存體觸發程序。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 屬性 ("path": "strings/{BlobName}") 來取得 Blob 名稱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