Azure Functions 觸發程序和繫結概念Azure Functions triggers and bindings concepts

本文是 Azure Functions 中觸發程序和繫結的概念性概觀。This article is a conceptual overview of triggers and bindings in Azure Functions. 這裡描述所有繫結及所有支援語言的通用功能。Features that are common to all bindings and all supported languages are described here.

概觀Overview

「觸發程序」會定義叫用函數的方式。A trigger defines how a function is invoked. 一個函數只能恰有一個觸發程序。A function must have exactly one trigger. 觸發程序具有相關聯的資料,它通常是觸發函數的承載。Triggers have associated data, which is usually the payload that triggered the function.

輸入和輸出「繫結」提供從您的程式碼內連線到資料的宣告式方法。Input and output bindings provide a declarative way to connect to data from within your code. 繫結是選擇性的,而且一個函數可以有多個輸入和輸出繫結。Bindings are optional and a function can have multiple input and output bindings.

觸發程序和繫結可讓您避免將正在使用的服務詳細資料硬式編碼。Triggers and bindings let you avoid hardcoding the details of the services that you're working with. 您的函式會接收函式參數中的資料 (例如佇列訊息的內容)。Your function receives data (for example, the content of a queue message) in function parameters. 您可以使用函式的傳回值來傳送資料 (例如用以建立佇列訊息)。You send data (for example, to create a queue message) by using the return value of the function. 在 C# 和 C# 指令碼中,傳送資料的方式可以是 out 參數和收集器物件In C# and C# script, alternative ways to send data are out parameters and collector objects.

當您使用 Azure 入口網站來開發函式時,觸發程序和繫結是在 function.json 檔案中進行設定。When you develop functions by using the Azure portal, triggers and bindings are configured in a function.json file. 入口網站提供此設定的 UI,但您可以變更為進階編輯器來直接編輯檔案。The portal provides a UI for this configuration but you can edit the file directly by changing to the Advanced editor.

當您使用 Visual Studio 建立類別庫來開發函式時,觸發程序和繫結是透過以屬性裝飾方法和參數來進行設定。When you develop functions by using Visual Studio to create a class library, you configure triggers and bindings by decorating methods and parameters with attributes.

觸發程序和繫結範例Example trigger and binding

假設您想要每當新訊息出現在 Azure 佇列儲存體時,就在 Azure 表格儲存體寫入新的資料列。Suppose you want to write a new row to Azure Table storage whenever a new message appears in Azure Queue storage. 此案例可以使用 Azure 佇列儲存體觸發程序和 Azure 表格儲存體輸出繫結來實作。This scenario can be implemented using an Azure Queue storage trigger and an Azure Table storage output binding.

以下是此案例的 function.json 檔案。Here's a function.json file for this scenario.

{
  "bindings": [
    {
      "name": "order",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue-items",
      "connection": "MY_STORAGE_ACCT_APP_SETTING"
    },
    {
      "name": "$return",
      "type": "table",
      "direction": "out",
      "tableName": "outTable",
      "connection": "MY_TABLE_STORAGE_ACCT_APP_SETTING"
    }
  ]
}

bindings 陣列中的第一個元素是佇列儲存體觸發程序。The first element in the bindings array is the Queue storage trigger. typedirection 屬性可識別觸發程序。The type and direction properties identify the trigger. name 屬性可識別會接收佇列訊息內容的函式參數。The name property identifies the function parameter that receives the queue message content. 要監視的佇列名稱是在 queueName 中,而連接字串則是在 connection 所識別的應用程式設定中。The name of the queue to monitor is in queueName, and the connection string is in the app setting identified by connection.

bindings 陣列中的第二個元素是 Azure 表格儲存體輸出繫結。The second element in the bindings array is the Azure Table Storage output binding. typedirection 屬性可識別繫結。The type and direction properties identify the binding. name 屬性指定函式如何提供新的資料表資料列,在本例中是透過函式傳回值。The name property specifies how the function provides the new table row, in this case by using the function return value. 資料表的名稱是在 tableName 中,而連接字串則是在 connection 所識別的應用程式設定中。The name of the table is in tableName, and the connection string is in the app setting identified by connection.

若要在 Azure 入口網站中檢視及編輯 function.json 的內容,請按一下函數的 [整合] 索引標籤上的 [進階編輯器] 選項。To view and edit the contents of function.json in the Azure portal, click the Advanced editor option on the Integrate tab of your function.

注意

connection 的值是包含連接字串的應用程式設定名稱,而不是連接字串本身。The value of connection is the name of an app setting that contains the connection string, not the connection string itself. 繫結使用儲存在應用程式設定中的連接字串,以強制遵循 function.json 不包含服務祕密的最佳做法。Bindings use connection strings stored in app settings to enforce the best practice that function.json does not contain service secrets.

以下是可搭配此觸發程序和繫結使用的 C# 指令碼。Here's C# script code that works with this trigger and binding. 請注意,提供佇列訊息內容的參數名稱為 order;由於 function.json 中的 name 屬性值為 order,因此必須使用此名稱Notice that the name of the parameter that provides the queue message content is order; this name is required because the name property value in function.json is order

#r "Newtonsoft.Json"

using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

// From an incoming queue message that is a JSON object, add fields and write to Table storage
// The method return value creates a new row in Table Storage
public static Person Run(JObject order, ILogger log)
{
    return new Person() { 
            PartitionKey = "Orders", 
            RowKey = Guid.NewGuid().ToString(),  
            Name = order["Name"].ToString(),
            MobileNumber = order["MobileNumber"].ToString() };  
}

public class Person
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
    public string MobileNumber { get; set; }
}

相同的 function.json 檔案可搭配 JavaScript 函式使用:The same function.json file can be used with a JavaScript function:

// From an incoming queue message that is a JSON object, add fields and write to Table Storage
// The second parameter to context.done is used as the value for the new row
module.exports = function (context, order) {
    order.PartitionKey = "Orders";
    order.RowKey = generateRandomId(); 

    context.done(null, order);
};

function generateRandomId() {
    return Math.random().toString(36).substring(2, 15) +
        Math.random().toString(36).substring(2, 15);
}

在類別庫中,會由屬性 (而非 function.json 檔案) 提供相同的觸發程序和繫結資訊 —佇列和資料表名稱、儲存體帳戶、輸入和輸出的函式參數—。In a class library, the same trigger and binding information — queue and table names, storage accounts, function parameters for input and output — is provided by attributes instead of a function.json file. 以下是範例:Here's an example:

 public static class QueueTriggerTableOutput
 {
     [FunctionName("QueueTriggerTableOutput")]
     [return: Table("outTable", Connection = "MY_TABLE_STORAGE_ACCT_APP_SETTING")]
     public static Person Run(
         [QueueTrigger("myqueue-items", Connection = "MY_STORAGE_ACCT_APP_SETTING")]JObject order, 
         ILogger log)
     {
         return new Person() {
                 PartitionKey = "Orders",
                 RowKey = Guid.NewGuid().ToString(),
                 Name = order["Name"].ToString(),
                 MobileNumber = order["MobileNumber"].ToString() };
     }
 }

 public class Person
 {
     public string PartitionKey { get; set; }
     public string RowKey { get; set; }
     public string Name { get; set; }
     public string MobileNumber { get; set; }
 }

支援的繫結Supported bindings

下表顯示兩個主要版本的 Azure Functions 執行階段中所支援的繫結。The following table shows the bindings that are supported in the two major versions of the Azure Functions runtime.

類型Type 1.x1.x 2.x12.x1 觸發程序Trigger 輸入Input 輸出Output
Blob 儲存體Blob Storage
Cosmos DBCosmos DB
Event GridEvent Grid
事件中樞Event Hubs
外部檔案2External File2
外部資料表2External Table2
HTTPHTTP
Microsoft Graph
Excel 資料表
Microsoft Graph
Excel tables
Microsoft Graph
OneDrive 檔案
Microsoft Graph
OneDrive files
Microsoft Graph
Outlook 電子郵件
Microsoft Graph
Outlook email
Microsoft Graph
事件
Microsoft Graph
Events
Microsoft Graph
驗證權杖
Microsoft Graph
Auth tokens
行動應用程式Mobile Apps
通知中樞Notification Hubs
佇列儲存體Queue storage
SendGridSendGrid
服務匯流排Service Bus
資料表儲存體Table storage
計時器Timer
TwilioTwilio
WebhookWebhooks

1 在 2.x 中,必須註冊 HTTP 和計時器以外的所有繫結。1 In 2.x, all bindings except HTTP and Timer must be registered. 請參閱註冊繫結延伸模組See Register binding extensions.

2不支援實驗性的 —,而且在未來可能會放棄。2 Experimental — not supported and might be abandoned in the future.

如需哪些繫結為預覽狀態或已核准可用於實際執行環境的資訊,請參閱支援的語言For information about which bindings are in preview or are approved for production use, see Supported languages.

註冊繫結延伸模組Register binding extensions

在某些開發環境中,您必須明確「註冊」您想要使用的繫結。In some development environments, you have to explicitly register a binding that you want to use. NuGet 套件中會提供繫結擴充功能,若要註冊擴充功能,則需安裝套件。Binding extensions are provided in NuGet packages, and to register an extension you install a package. 下表指出何時要註冊繫結擴充功能,以及註冊方式。The following table indicates when and how you register binding extensions.

開發環境Development environment 註冊Registration
在 Functions 1.x 中in Functions 1.x
註冊Registration
在 Functions 2.x 中in Functions 2.x
Azure 入口網站Azure portal 自動Automatic 自動 (含提示)Automatic with prompt
在本機使用 Azure Functions 核心工具Local using Azure Functions Core Tools 自動Automatic 使用核心工具 CLI 命令Use Core Tools CLI commands
使用 Visual Studio 2017 的 C# 類別庫C# class library using Visual Studio 2017 使用 NuGet 工具Use NuGet tools 使用 NuGet 工具Use NuGet tools
使用 Visual Studio Code 的 C# 類別庫C# class library using Visual Studio Code N/AN/A 使用 .NET Core CLIUse .NET Core CLI

下列繫結類型是例外,不需要明確註冊,因為這些類型會在所有版本和環境中自動註冊:HTTP 與計時器。The following binding types are exceptions that don't require explicit registration because they are automatically registered in all versions and environments: HTTP and timer.

Azure 入口網站開發Azure portal development

本節僅適用於 Functions 2.x。This section applies only to Functions 2.x. 繫結延伸模組不需要先在 Functions 1.x 中明確註冊。Binding extensions don't have to be explicitly registered in Functions 1.x.

當您建立函式或新增繫結時,系統會在觸發程序或繫結的擴充功能需要註冊時提示您。When you create a function or add a binding, you are prompted when the extension for the trigger or binding requires registration. 請按一下 [安裝] 來註冊擴充功能,以回應提示。Respond to the prompt by clicking Install to register the extension. 安裝在取用方案上可能需要多達 10 分鐘。Installation can take up to 10 minutes on a consumption plan.

針對指定的函式應用程式,您只須安裝每個延伸模組一次。You need only install each extension one time for a given function app. 針對已支援但在入口網站中未提供的繫結,或是若要更新已安裝的延伸模組,您也可以從入口網站手動安裝或更新 Azure Functions 繫結延伸模組For supported bindings that are not available in the portal or to update the an installed extension, you can also manually install or update Azure Functions binding extensions from the portal.

本機開發 Azure Functions Core ToolsLocal development Azure Functions Core Tools

本節僅適用於 Functions 2.x。This section applies only to Functions 2.x. 繫結延伸模組不需要先在 Functions 1.x 中明確註冊。Binding extensions don't have to be explicitly registered in Functions 1.x.

當您在本機開發函式時,您可以從終端機或命令提示字元中使用 Azure Functions Core Tools,來安裝需要的擴充。When you develop functions locally, you can install the extensions you need by using the Azure Functions Core Tools from the Terminal or from a command prompt.

在更新 function.json 檔案以包含函式所需的所有繫結後,請在專案資料夾中執行下列命令。After you have updated your function.json file to include all the bindings that your function needs, run the following command in the project folder.

func extensions install

此命令會讀取 function.json 檔案,查看您需要哪些套件,加以安裝,然後重建擴充專案。The command reads the function.json file to see which packages you need, installs them, and rebuilds the extensions project. 它會在目前版本中新增任何新繫結,但不會更新現有的繫結。It adds any new bindings at the current version but does not update existing bindings. 在安裝新的繫結時,使用 --force 選項將現有繫結更新為最新版本。Use the --force option to update existing bindings to the latest version when installing new ones.

如果您想要安裝特定版本的套件,或是要在編輯 function.json 檔案之前安裝套件,請使用 func extensions install 命令搭配套件的名稱,如下列範例所示:If you want to install a particular version of a package or you want to install packages before editing the function.json file, use the func extensions install command with the name of the package, as shown in the following example:

func extensions install --package Microsoft.Azure.WebJobs.ServiceBus --version <target_version>

以特定版本的套件取代 <target_version>,例如 3.0.0-beta5Replace <target_version> with a specific version of the package, such as 3.0.0-beta5. 有效的版本會列在 NuGet.org 的個別套件頁面上。Valid versions are listed on the individual package pages at NuGet.org.

包含 Visual Studio 2017 的 C# 類別庫C# class library with Visual Studio 2017

Visual Studio 2017 中,您可以使用 Install-Package 命令,從「套件管理員主控台」中安裝套件,如下列範例所示:In Visual Studio 2017, you can install packages from the Package Manager Console using the Install-Package command, as shown in the following example:

Install-Package Microsoft.Azure.WebJobs.Extensions.ServiceBus -Version <target_version>

在指定繫結的參考文章中,會提供要用於該繫結的套件名稱。The name of the package to use for a given binding is provided in the reference article for that binding. 如需範例,請參閱服務匯流排繫結參考文章的套件一節For an example, see the Packages section of the Service Bus binding reference article.

請以特定版本的套件 (例如 3.0.0-beta5) 取代範例中的 <target_version>Replace <target_version> in the example with a specific version of the package, such as 3.0.0-beta5. 有效的版本會列在 NuGet.org 的個別套件頁面上。對應至 Functions 執行階段 1.x 或 2.x 的主要版本,會在繫結的參考文章中指定。Valid versions are listed on the individual package pages at NuGet.org. The major versions that correspond to Functions runtime 1.x or 2.x are specified in the reference article for the binding.

包含 Visual Studio Code 的 C# 類別庫C# class library with Visual Studio Code

Visual Studio Code 中,您可以在 .NET Core CLI 中使用 dotnet add package 命令,從命令提示字元安裝套件,如下列範例所示:In Visual Studio Code, you can install packages from the command prompt using the dotnet add package command in the .NET Core CLI, as shown in the following example:

dotnet add package Microsoft.Azure.WebJobs.Extensions.ServiceBus --version <target_version>

.NET Core CLI 只能用於 Azure Functions 2.x 開發。The .NET Core CLI can only be used for Azure Functions 2.x development.

在指定繫結的參考文章中,會提供要用於該繫結的套件名稱。The name of the package to use for a given binding is provided in the reference article for that binding. 如需範例,請參閱服務匯流排繫結參考文章的套件一節For an example, see the Packages section of the Service Bus binding reference article.

請以特定版本的套件 (例如 3.0.0-beta5) 取代範例中的 <target_version>Replace <target_version> in the example with a specific version of the package, such as 3.0.0-beta5. 有效的版本會列在 NuGet.org 的個別套件頁面上。對應至 Functions 執行階段 1.x 或 2.x 的主要版本,會在繫結的參考文章中指定。Valid versions are listed on the individual package pages at NuGet.org. The major versions that correspond to Functions runtime 1.x or 2.x are specified in the reference article for the binding.

繫結方向Binding direction

所有觸發程序和繫結在 function.json 檔案中都具有 direction 屬性:All triggers and bindings have a direction property in the function.json file:

  • 對於觸發程序,方向一律為 inFor triggers, the direction is always in
  • 輸入和輸出繫結使用 inoutInput and output bindings use in and out
  • 某些繫結支援特殊方向 inoutSome bindings support a special direction inout. 如果您使用 inout,則 [整合] 索引標籤中只有 [進階編輯器] 可供使用。If you use inout, only the Advanced editor is available in the Integrate tab.

當您使用類別庫中的屬性來設定觸發程序和繫結時,請在屬性建構函式中提供方向,或從參數類型推斷方向。When you use attributes in a class library to configure triggers and bindings, the direction is provided in an attribute constructor or inferred from the parameter type.

使用函式傳回值Using the function return value

在具有傳回值的語言中,您可以將「輸出繫結」繫結至傳回值:In languages that have a return value, you can bind an output binding to the return value:

  • 在 C# 類別庫中,將輸出繫結屬性套用至方法傳回值。In a C# class library, apply the output binding attribute to the method return value.
  • 在其他語言中,將 function.json 中的 name 屬性設定為 $returnIn other languages, set the name property in function.json to $return.

如果有多個輸出繫結,請只對其中一個使用傳回值。If there are multiple output bindings, use the return value for only one of them.

在 C# 和 C# 指令碼中,傳送資料到輸出繫結的方式可以是 out 參數和收集器物件In C# and C# script, alternative ways to send data to an output binding are out parameters and collector objects.

請參閱示範傳回值用法的特定語言範例:See the language-specific example showing use of the return value:

C# 範例C# example

以下是使用輸出繫結傳回值的 C# 程式碼,接著則是非同步範例:Here's C# code that uses the return value for an output binding, followed by an async example:

[FunctionName("QueueTrigger")]
[return: Blob("output-container/{id}")]
public static string Run([QueueTrigger("inputqueue")]WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return json;
}
[FunctionName("QueueTrigger")]
[return: Blob("output-container/{id}")]
public static Task<string> Run([QueueTrigger("inputqueue")]WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return Task.FromResult(json);
}

C# 指令碼範例C# script example

以下是 function.json 檔案中的輸出繫結:Here's the output binding in the function.json file:

{
    "name": "$return",
    "type": "blob",
    "direction": "out",
    "path": "output-container/{id}"
}

以下是 C# 指令程式碼,接著則是非同步範例:Here's the C# script code, followed by an async example:

public static string Run(WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return json;
}
public static Task<string> Run(WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return Task.FromResult(json);
}

F# 範例F# example

以下是 function.json 檔案中的輸出繫結:Here's the output binding in the function.json file:

{
    "name": "$return",
    "type": "blob",
    "direction": "out",
    "path": "output-container/{id}"
}

以下是 F# 程式碼:Here's the F# code:

let Run(input: WorkItem, log: ILogger) =
    let json = String.Format("{{ \"id\": \"{0}\" }}", input.Id)   
    log.LogInformation(sprintf "F# script processed queue message '%s'" json)
    json

JavaScript 範例JavaScript example

以下是 function.json 檔案中的輸出繫結:Here's the output binding in the function.json file:

{
    "name": "$return",
    "type": "blob",
    "direction": "out",
    "path": "output-container/{id}"
}

在 JavaScript 中,傳回值是放在 context.done 的第二個參數中:In JavaScript, the return value goes in the second parameter for context.done:

module.exports = function (context, input) {
    var json = JSON.stringify(input);
    context.log('Node.js script processed queue message', json);
    context.done(null, json);
}

繫結 dataType 屬性Binding dataType property

在 .NET 中,使用參數類型可定義輸入資料的資料類型。In .NET, use the parameter type to define the data type for input data. 例如,使用 string 繫結至要以二進位格式和自訂類型讀取以還原序列化為 POCO 物件之佇列觸發程序和位元組陣列的文字。For instance, use string to bind to the text of a queue trigger, a byte array to read as binary and a custom type to deserialize to a POCO object.

對於 JavaScript 等具有動態類型的語言,則會使用 function.json 檔案中的 dataType 屬性。For languages that are dynamically typed such as JavaScript, use the dataType property in the function.json file. 例如,若要讀取二進位格式的 HTTP 要求內容,請將 dataType 設定為 binaryFor example, to read the content of an HTTP request in binary format, set dataType to binary:

{
    "type": "httpTrigger",
    "name": "req",
    "direction": "in",
    "dataType": "binary"
}

dataType 也另具有 streamstring 兩種選項。Other options for dataType are stream and string.

繫結運算式和模式Binding expressions and 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}");
}

繫結運算式 - 觸發程序檔案名稱Binding expressions - 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.

繫結運算式 - 觸發程序中繼資料Binding expressions - 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 承載Binding expressions - 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; }
}

繫結運算式 - 建立 GUIDBinding expressions - create 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}"
}

繫結運算式 - 目前時間Binding expressions - 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.

function.json 檔案結構描述function.json file schema

function.json 檔案結構描述可以在 http://json.schemastore.org/function 取得。The function.json file schema is available at http://json.schemastore.org/function.

處理繫結錯誤Handling binding errors

Azure Functions 觸發程序和繫結會與各種 Azure 服務通訊。Azure Functions triggers and bindings communicate with various Azure services. 在與這些服務整合時,您可能會引發錯誤,而這些錯誤是源自基礎 Azure 服務的 API。When integrating with these services, you may have errors raised that originate from the APIs of the underlying Azure services. 當您嘗試使用 REST 或用戶端程式庫,透過您的函式程式碼與其他服務通訊時,也可能會發生錯誤。Errors can also occur when you try to communicate with other services from your function code by using REST or client libraries. 若要避免遺失資料並確保函式有正常行為,請務必要處理來自上述任一來源的錯誤。To avoid loss of data and ensure good behavior of your functions, it is important to handle errors from either source.

下列觸發程序有內建的重試支援:The following triggers have built-in retry support:

根據預設,這些觸發程序最多會重試五次。By default, these triggers are retried up to five times. 在第五次重試之後,這些觸發程序就會在特殊的有害佇列中寫入一則訊息。After the fifth retry, these triggers write a message to a special poison queue.

其他 Functions 觸發程序並未內建可在函式執行期間發生錯誤時進行重試的機制。For the other Functions triggers, there is no built-in retry when errors occur during function execution. 為了避免在萬一函式發生錯誤時遺失觸發程序資訊,建議您在函式程式碼中使用 try-catch 區塊,以擷取任何錯誤。To prevent loss of trigger information should an error occur in your function, we recommend that you use try-catch blocks in your function code to catch any errors. 當錯誤發生時,請將觸發程序傳遞至函式的資訊寫入至特殊的「有害」訊息佇列。When an error occurs, write the information passed into the function by the trigger to a special "poison" message queue. 這個方法和 Blob 儲存體觸發程序所使用的方法相同。This approach is the same one used by the Blob storage trigger.

如此一來,您就可以擷取可能會因錯誤而遺失的觸發程序事件,並於稍後使用其他函式來重試這些事件,以使用所儲存的資訊處理有害佇列中的訊息。In this way, you can capture trigger events that could be lost due to errors and retry them at a later time using another function to process messages from the poison queue using the stored information.

如需 Functions 所支援各種服務的所有相關錯誤主題連結,請參閱Azure Functions 錯誤處理 (英文) 概觀主題的繫結錯誤碼一節。For links to all relevant error topics for the various services supported by Functions, see the Binding error codes section of the Azure Functions error handling overview topic.

後續步驟Next steps

如需特定繫結的詳細資訊,請參閱下列文章:For more information on a specific binding, see the following articles: