Azure Functions 的 Event Grid 觸發程序Event Grid trigger for Azure Functions

本文說明如何在 Azure Functions 中處理 Event Grid 事件。This article explains how to handle Event Grid events in Azure Functions.

Event Grid 是一項 Azure 服務,會傳送 HTTP 要求通知您「發行者」 中發生的事件。Event Grid is an Azure service that sends HTTP requests to notify you about events that happen in publishers. 發行者是產生事件的服務或資源。A publisher is the service or resource that originates the event. 例如,Azure Blob 儲存體帳戶即為發行者,而 Blob 的上傳或刪除是事件For example, an Azure blob storage account is a publisher, and a blob upload or deletion is an event. 部分 Azure 服務內建有將事件發佈至 Event Grid 的支援Some Azure services have built-in support for publishing events to Event Grid.

事件處理常式會接收及處理事件。Event handlers receive and process events. Azure Functions 是數個有內建 Event Grid 事件處理支援的 Azure 服務之一。Azure Functions is one of several Azure services that have built-in support for handling Event Grid events. 在本文中,您將了解如何在接收到來自 Event Grid 的事件時使用 Event Grid 觸發程序來叫用函式。In this article, you learn how to use an Event Grid trigger to invoke a function when an event is received from Event Grid.

如果您想要的話,您可以使用 HTTP 觸發程序來處理 Event Grid 事件;請參閱本文稍後的以 HTTP 觸發程序作為 Event Grid 觸發程序If you prefer, you can use an HTTP trigger to handle Event Grid Events; see Use an HTTP trigger as an Event Grid trigger later in this article. 目前,當事件是在 CloudEvents 結構描述中傳遞時,您無法針對 Azure Functions 應用程式使用事件格線觸發程序。Currently, you can't use an Event Grid trigger for an Azure Functions app when the event is delivered in the CloudEvents schema. 相反地,請使用 HTTP 觸發程序。Instead, use an HTTP trigger.

這是 Azure Functions 開發人員的參考資訊。This is reference information for Azure Functions developers. 如果您不熟悉 Azure Functions,請從下列資源開始︰If you're new to Azure Functions, start with the following resources:

套件 - Functions 2.xPackages - Functions 2.x

Microsoft.Azure.WebJobs.Extensions.EventGrid NuGet 套件 2.x 版中提供 Event Grid 觸發程序。The Event Grid trigger is provided in the Microsoft.Azure.WebJobs.Extensions.EventGrid NuGet package, version 2.x. 套件的原始程式碼位於 azure-functions-eventgrid-extension GitHub 存放庫中。Source code for the package is in the azure-functions-eventgrid-extension GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 若要新增支援To add support in
Functions 2.xFunctions 2.x
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#、Java 和 PythonLocal development - C# script, JavaScript, F#, Java and Python 註冊擴充功能Register the extension
入口網站開發Portal development 在新增輸出繫結時安裝Install when adding output binding

若要了解如何在不重新發行您的函數應用程式專案的情況下在入口網站中更新現有的繫結延伸模組,請參閱更新您的延伸模組To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.

套件 - Functions 1.xPackages - Functions 1.x

Microsoft.Azure.WebJobs.Extensions.EventGrid NuGet 套件 1.x 版中提供 Event Grid 觸發程序。The Event Grid trigger is provided in the Microsoft.Azure.WebJobs.Extensions.EventGrid NuGet package, version 1.x. 套件的原始程式碼位於 azure-functions-eventgrid-extension GitHub 存放庫中。Source code for the package is in the azure-functions-eventgrid-extension GitHub repository.

下表說明如何在每個開發環境中為此繫結新增支援。The following table tells how to add support for this binding in each development environment.

開發環境Development environment 若要新增支援To add support in
Functions 1.xFunctions 1.x
本機開發 - C# 類別庫Local development - C# class library 安裝套件Install the package
本機開發 - C# 指令碼、JavaScript、F#Local development - C# script, JavaScript, F# 自動Automatic
入口網站開發Portal development 自動Automatic

範例Example

請參閱 Event Grid 觸發程序的語言特定範例:See the language-specific example for an Event Grid trigger:

如需 HTTP 觸發程序範例,請參閱本文稍後的如何使用 HTTP 觸發程序For an HTTP trigger example, see How to use HTTP trigger later in this article.

C# (2.x)C# (2.x)

下列範例顯示繫結至 EventGridEvent 的 Functions 2.x C# 函式The following example shows a Functions 2.x C# function that binds to EventGridEvent:

using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerCSharp
    {
        [FunctionName("EventGridTest")]
        public static void EventGridTest([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());
        }
    }
}

如需詳細資訊,請參閱套件、屬性設定用法For more information, see Packages, Attributes, Configuration, and Usage.

C# (1.x 版)C# (Version 1.x)

下列範例顯示繫結至 JObject 的 Functions 1.x C# 函式The following example shows a Functions 1.x C# function that binds to JObject:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerCSharp
    {
        [FunctionName("EventGridTriggerCSharp")]
        public static void Run([EventGridTrigger]JObject eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.ToString(Formatting.Indented));
        }
    }
}

C# 指令碼範例C# script example

下列範例示範 function.json 檔案中的觸發程序繫結,以及使用此繫結的 C# 指令碼函式The following example shows a trigger binding in a function.json file and a C# script function that uses the binding.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

C# 指令碼 (2.x 版)C# script (Version 2.x)

以下是繫結至 EventGridEvent 的 Functions 2.x C# 指令碼:Here's Functions 2.x C# script code that binds to EventGridEvent:

#r "Microsoft.Azure.EventGrid"
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;

public static void Run(EventGridEvent eventGridEvent, ILogger log)
{
    log.LogInformation(eventGridEvent.Data.ToString());
}

如需詳細資訊,請參閱套件、屬性設定用法For more information, see Packages, Attributes, Configuration, and Usage.

C# 指令碼 (1.x 版)C# script (Version 1.x)

以下是繫結至 JObject 的 Functions 1.x C# 指令碼:Here's Functions 1.x C# script code that binds to JObject:

#r "Newtonsoft.Json"

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static void Run(JObject eventGridEvent, TraceWriter log)
{
    log.Info(eventGridEvent.ToString(Formatting.Indented));
}

JavaScript 範例JavaScript example

下列範例示範的是使用繫結之 function.json 檔案,以及 JavaScript 函式中的觸發程序繫結。The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

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

module.exports = function (context, eventGridEvent) {
    context.log("JavaScript Event Grid function processed a request.");
    context.log("Subject: " + eventGridEvent.subject);
    context.log("Time: " + eventGridEvent.eventTime);
    context.log("Data: " + JSON.stringify(eventGridEvent.data));
    context.done();
};

Python 範例Python example

下列範例示範 function.json 檔案中的觸發程序繫結,以及使用此繫結的 Python 函式The following example shows a trigger binding in a function.json file and a Python function that uses the binding.

以下是 function.json 檔案中的繫結資料:Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "event",
      "direction": "in"
    }
  ],
  "disabled": false,
  "scriptFile": "__init__.py"
}

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

import logging
import azure.functions as func


def main(event: func.EventGridEvent):
    logging.info("Python Event Grid function processed a request.")
    logging.info("  Subject: %s", event.subject)
    logging.info("  Time: %s", event.event_time)
    logging.info("  Data: %s", event.get_json())

觸發程序 - Java 範例Trigger - Java examples

本區段包含下列範例:This section contains the following examples:

下列範例會在 function.json 檔案中顯示觸發程序繫結,以及使用該繫結並印出事件的 Java 函式,其會將第一次接收事件當作 String,並將第二次當作 POJO。The following examples show trigger binding in a function.json file and Java functions that use the binding and print out an event, first receiving the event as String and second as a POJO.

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ]
}

事件格線觸發程序,字串參數 (Java)Event Grid trigger, String parameter (Java)

  @FunctionName("eventGridMonitorString")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    ) 
    String content, 
    final ExecutionContext context) {
      // log 
      context.getLogger().info("Event content: " + content);      
  }

事件格線觸發程序,POJO 參數 (Java)Event Grid trigger, POJO parameter (Java)

此範例會使用下列 POJO 來代表事件格線事件的最上層屬性:This example uses the following POJO, representing the top-level properties of an Event Grid event:

import java.util.Date;
import java.util.Map;

public class EventSchema {

  public String topic;
  public String subject;
  public String eventType;
  public Date eventTime;
  public String id;
  public String dataVersion;
  public String metadataVersion;
  public Map<String, Object> data;

}

抵達時,會將事件的 JSON 承載還原序列化為 EventSchema POJO,以供函式使用。Upon arrival, the event's JSON payload is de-serialized into the EventSchema POJO for use by the function. 這可讓函式以物件導向方式存取事件的屬性。This allows the function to access the event's properties in an object-oriented way.

  @FunctionName("eventGridMonitor")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    ) 
    EventSchema event, 
    final ExecutionContext context) {
      // log 
      context.getLogger().info("Event content: ");
      context.getLogger().info("Subject: " + event.subject);
      context.getLogger().info("Time: " + event.eventTime); // automatically converted to Date by the runtime
      context.getLogger().info("Id: " + event.id);
      context.getLogger().info("Data: " + event.data);
  }

Java 函式執行階段程式庫中,對其值來自事件方格的參數使用 EventGridTrigger 註釋。In the Java functions runtime library, use the EventGridTrigger annotation on parameters whose value would come from EventGrid. 具有這些附註的參數會使得函式在事件抵達時執行。Parameters with these annotations cause the function to run when an event arrives. 此註釋可以搭配原生 Java 類型、POJO 或使用 Optional<T> 的可為 Null 值使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

屬性Attributes

C# 類別庫中,使用 EventGridTrigger 屬性。In C# class libraries, use the EventGridTrigger attribute.

以下是方法簽章中的 EventGridTrigger 屬性:Here's an EventGridTrigger attribute in a method signature:

[FunctionName("EventGridTest")]
public static void EventGridTest([EventGridTrigger] JObject eventGridEvent, ILogger log)
{
    ...
}

如需完整範例,請參閱 C# 範例。For a complete example, see C# example.

組態Configuration

下表說明您在 function.json 檔案中設定的繫結設定屬性。The following table explains the binding configuration properties that you set in the function.json file. 沒有要在 EventGridTrigger 屬性中設定的建構函式參數或屬性。There are no constructor parameters or properties to set in the EventGridTrigger attribute.

function.json 屬性function.json property 描述Description
typetype 必要項目 - 必須設定為 eventGridTriggerRequired - must be set to eventGridTrigger.
directiondirection 必要項目 - 必須設定為 inRequired - must be set to in.
namename 必要項目 - 函式程式碼中用於接收事件資料之參數的變數名稱。Required - the variable name used in function code for the parameter that receives the event data.

使用量Usage

使用 Azure Functions 1.x 中的 C# 和 F# 函式時,您可以為 Event Grid 觸發程序使用下列參數類型:For C# and F# functions in Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

  • JObject
  • string

使用 Azure Functions 2.x 中的 C# 和 F# 函式時,您也可以為 Event Grid 觸發程序使用下列參數類型:For C# and F# functions in Azure Functions 2.x, you also have the option to use the following parameter type for the Event Grid trigger:

  • Microsoft.Azure.EventGrid.Models.EventGridEvent - 定義所有事件類型通用之欄位的屬性。Microsoft.Azure.EventGrid.Models.EventGridEvent- Defines properties for the fields common to all event types.

注意

在 Functions v1 中,如果您嘗試繫結至 Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent,編譯器將會顯示「已淘汰」訊息,並建議您改用 Microsoft.Azure.EventGrid.Models.EventGridEventIn Functions v1 if you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler will display a "deprecated" message and advise you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. 若要使用較新的類型,請參考 Microsoft.Azure.EventGrid NuGet 套件,並且為 EventGridEvent 類型名稱加上 Microsoft.Azure.EventGrid.Models 首碼,加以完整限定。To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models. 如需如何在 C# 指令碼函式中參考 NuGet 套件的相關資訊,請參閱使用 NuGet 套件For information about how to reference NuGet packages in a C# script function, see Using NuGet packages

對於 JavaScript 函式,由 function.json name 屬性命名的參數會參考事件物件。For JavaScript functions, the parameter named by the function.json name property has a reference to the event object.

結構描述Event schema

接收到的 Event Grid 事件資料,會是 HTTP 要求本文中的 JSON 物件。Data for an Event Grid event is received as a JSON object in the body of an HTTP request. 此 JSON 大致如下列範例所示:The JSON looks similar to the following example:

[{
  "topic": "/subscriptions/{subscriptionid}/resourceGroups/eg0122/providers/Microsoft.Storage/storageAccounts/egblobstore",
  "subject": "/blobServices/default/containers/{containername}/blobs/blobname.jpg",
  "eventType": "Microsoft.Storage.BlobCreated",
  "eventTime": "2018-01-23T17:02:19.6069787Z",
  "id": "{guid}",
  "data": {
    "api": "PutBlockList",
    "clientRequestId": "{guid}",
    "requestId": "{guid}",
    "eTag": "0x8D562831044DDD0",
    "contentType": "application/octet-stream",
    "contentLength": 2248,
    "blobType": "BlockBlob",
    "url": "https://egblobstore.blob.core.windows.net/{containername}/blobname.jpg",
    "sequencer": "000000000000272D000000000003D60F",
    "storageDiagnostics": {
      "batchId": "{guid}"
    }
  },
  "dataVersion": "",
  "metadataVersion": "1"
}]

範例中顯示一個元素的陣列。The example shown is an array of one element. Event Grid 一律會傳送陣列,且在陣列中可能會傳送多個事件。Event Grid always sends an array and may send more than one event in the array. 執行階段分別會為每個陣列元素叫用您的函式一次。The runtime invokes your function once for each array element.

所有事件類型的事件 JSON 資料中會具有相同的最上層屬性,但 data 屬性的內容則會隨著事件類型而不同。The top-level properties in the event JSON data are the same among all event types, while the contents of the data property are specific to each event type. 此處顯示的是 Blob 儲存體事件的範例。The example shown is for a blob storage event.

如需通用屬性和事件特定屬性的說明,請參閱 Event Grid 文件中的事件屬性For explanations of the common and event-specific properties, see Event properties in the Event Grid documentation.

EventGridEvent 類型只會定義最上層屬性;Data 屬性為 JObjectThe EventGridEvent type defines only the top-level properties; the Data property is a JObject.

建立訂用帳戶Create a subscription

若要開始接收 Event Grid HTTP 要求,請建立會指定端點 URL 以叫用函式的 Event Grid 訂用帳戶。To start receiving Event Grid HTTP requests, create an Event Grid subscription that specifies the endpoint URL that invokes the function.

Azure 入口網站Azure portal

對於您在 Azure 入口網站中使用 Event Grid 觸發程序開發的函式,選取新增 Event Grid 訂用帳戶For functions that you develop in the Azure portal with the Event Grid trigger, select Add Event Grid subscription.

在入口網站中建立訂用帳戶

當您選取此連結時,入口網站會開啟預先填入端點 URL 的建立事件訂用帳戶頁面。When you select this link, the portal opens the Create Event Subscription page with the endpoint URL prefilled.

預先填入的端點 URL

如需如何使用 Azure 入口網站建立訂用帳戶的詳細資訊,請參閱 Event Grid 文件中的建立自訂事件 - Azure 入口網站For more information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

Azure CLIAzure CLI

若要使用 Azure CLI 建立訂用帳戶,請使用 az eventgrid event-subscription create 命令。To create a subscription by using the Azure CLI, use the az eventgrid event-subscription create command.

此命令需要叫用函式的端點 URL。The command requires the endpoint URL that invokes the function. 下列範例顯示特定版本的 URL 模式:The following example shows the version-specific URL pattern:

2.x 版執行階段Version 2.x runtime

https://{functionappname}.azurewebsites.net/runtime/webhooks/eventgrid?functionName={functionname}&code={systemkey}

1.x 版執行階段Version 1.x runtime

https://{functionappname}.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName={functionname}&code={systemkey}

系統金鑰是必須包含在端點 URL 中供 Event Grid 觸發程序使用的授權金鑰。The system key is an authorization key that has to be included in the endpoint URL for an Event Grid trigger. 下一節將說明如何取得系統金鑰。The following section explains how to get the system key.

以下是訂閱 Blob 儲存體帳戶的範例 (以預留位置表示系統金鑰):Here's an example that subscribes to a blob storage account (with a placeholder for the system key):

2.x 版執行階段Version 2.x runtime

az eventgrid resource event-subscription create -g myResourceGroup \
--provider-namespace Microsoft.Storage --resource-type storageAccounts \
--resource-name myblobstorage12345 --name myFuncSub  \
--included-event-types Microsoft.Storage.BlobCreated \
--subject-begins-with /blobServices/default/containers/images/blobs/ \
--endpoint https://mystoragetriggeredfunction.azurewebsites.net/runtime/webhooks/eventgrid?functionName=imageresizefunc&code=<key>

1.x 版執行階段Version 1.x runtime

az eventgrid resource event-subscription create -g myResourceGroup \
--provider-namespace Microsoft.Storage --resource-type storageAccounts \
--resource-name myblobstorage12345 --name myFuncSub  \
--included-event-types Microsoft.Storage.BlobCreated \
--subject-begins-with /blobServices/default/containers/images/blobs/ \
--endpoint https://mystoragetriggeredfunction.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName=imageresizefunc&code=<key>

如需如何建立訂用帳戶的詳細資訊,請參閱 Blob 儲存體快速入門或其他 Event Grid 快速入門。For more information about how to create a subscription, see the blob storage quickstart or the other Event Grid quickstarts.

取得系統金鑰Get the system key

您可以使用下列 API (HTTP GET) 來取得系統金鑰:You can get the system key by using the following API (HTTP GET):

2.x 版執行階段Version 2.x runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgrid_extension?code={masterkey}

1.x 版執行階段Version 1.x runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgridextensionconfig_extension?code={masterkey}

這是管理員 API,因此需要函式應用程式的主要金鑰This is an admin API, so it requires your function app master key. 請勿混淆系統金鑰 (用來叫用事件方格觸發程序函式) 與主要金鑰 (用來執行函式應用程式的管理工作)。Don't confuse the system key (for invoking an Event Grid trigger function) with the master key (for performing administrative tasks on the function app). 當您訂閱 Event Grid 主題時,請務必使用系統金鑰。When you subscribe to an Event Grid topic, be sure to use the system key.

以下範例說明提供系統金鑰的回應:Here's an example of the response that provides the system key:

{
  "name": "eventgridextensionconfig_extension",
  "value": "{the system key for the function}",
  "links": [
    {
      "rel": "self",
      "href": "{the URL for the function, without the system key}"
    }
  ]
}

您可以從入口網站中的 [函數應用程式設定] 索引標籤取得函數應用程式主要金鑰。You can get the master key for your function app from the Function app settings tab in the portal.

重要

主要金鑰為系統管理員提供對函數應用程式的存取權。The master key provides administrator access to your function app. 請勿與第三方共用此金鑰或將其散發於原生用戶端應用程式。Don't share this key with third parties or distribute it in native client applications.

如需詳細資訊,請參閱 HTTP 觸發程序參考文章中的授權金鑰For more information, see Authorization keys in the HTTP trigger reference article.

或者,您可以傳送 HTTP PUT 以自行指定金鑰值。Alternatively, you can send an HTTP PUT to specify the key value yourself.

使用檢視器 Web 應用程式的本機測試Local testing with viewer web app

若要在本機測試 Event Grid 觸發程序,您必須取得從雲端中的原有位置傳遞到本機電腦的 Event Grid HTTP 要求。To test an Event Grid trigger locally, you have to get Event Grid HTTP requests delivered from their origin in the cloud to your local machine. 其中一種方式是在線上擷取要求,然後手動將其重新傳送至您的本機電腦:One way to do that is by capturing requests online and manually resending them on your local machine:

  1. 建立檢視器 Web 應用程式,以擷取事件訊息。Create a viewer web app that captures event messages.
  2. 建立事件格線訂用帳戶,以將事件傳送至檢視器應用程式。Create an Event Grid subscription that sends events to the viewer app.
  3. 產生要求,並從檢視器應用程式複製要求本文。Generate a request and copy the request body from the viewer app.
  4. 手動將要求發佈至 Event Grid 觸發程序函式的 localhost URL。Manually post the request to the localhost URL of your Event Grid trigger function.

完成測試後,您可以藉由更新端點,在生產環境使用相同的訂用帳戶。When you're done testing, you can use the same subscription for production by updating the endpoint. 使用 az eventgrid event-subscription update Azure CLI 命令。Use the az eventgrid event-subscription update Azure CLI command.

建立檢視器 Web 應用程式Create a viewer web app

若要簡化擷取事件訊息,您可以部署預先建置的 Web 應用程式,以顯示事件訊息。To simplify capturing event messages, you can deploy a pre-built web app that displays the event messages. 已部署的解決方案包含 App Service 方案、App Service Web 應用程式,以及 GitHub 中的原始程式碼。The deployed solution includes an App Service plan, an App Service web app, and source code from GitHub.

選取 [部署至 Azure] ,將解決方案部署至您的訂用帳戶。Select Deploy to Azure to deploy the solution to your subscription. 在 Azure 入口網站中,提供參數的值。In the Azure portal, provide values for the parameters.

部署需要幾分鐘的時間才能完成。The deployment may take a few minutes to complete. 成功部署之後,檢視 Web 應用程式,確定它正在執行。After the deployment has succeeded, view your web app to make sure it's running. 在網頁瀏覽器中,瀏覽至:https://<your-site-name>.azurewebsites.netIn a web browser, navigate to: https://<your-site-name>.azurewebsites.net

您看到網站,但其中尚未發佈任何事件。You see the site but no events have been posted to it yet.

檢視新網站

建立事件格線訂用帳戶Create an Event Grid subscription

建立您想要測試之類型的事件格線訂用帳戶,並從您的 Web 應用程式提供其 URL 作為端點的事件通知。Create an Event Grid subscription of the type you want to test, and give it the URL from your web app as the endpoint for event notification. Web 應用程式的端點必須包含的尾碼 /api/updates/The endpoint for your web app must include the suffix /api/updates/. 因此,完整 URL 是 https://<your-site-name>.azurewebsites.net/api/updatesSo, the full URL is https://<your-site-name>.azurewebsites.net/api/updates

如需如何使用 Azure 入口網站建立訂用帳戶的資訊,請參閱事件格線文件中的建立自訂事件 - Azure 入口網站For information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

產生要求Generate a request

觸發會對您的 Web 應用程式端點產生 HTTP 流量的事件。Trigger an event that will generate HTTP traffic to your web app endpoint. 例如,如果您已建立 Blob 儲存體訂用帳戶,請上傳或刪除 Blob。For example, if you created a blob storage subscription, upload or delete a blob. 當要求出現在 Web 應用程式上時,請複製要求本文。When a request shows up in your web app, copy the request body.

您會先收到訂用帳戶驗證要求;請忽略任何驗證要求,並複製事件要求。The subscription validation request will be received first; ignore any validation requests, and copy the event request.

從 Web 應用程式複製要求本文

手動發佈要求Manually post the request

在本機執行您的 Event Grid 函式。Run your Event Grid function locally.

使用 Postmancurl 之類的工具建立 HTTP POST 要求:Use a tool such as Postman or curl to create an HTTP POST request:

  • 設定 Content-Type: application/json 標頭。Set a Content-Type: application/json header.
  • 設定 aeg-event-type: Notification 標頭。Set an aeg-event-type: Notification header.
  • 將 RequestBin 資料貼到要求本文中。Paste the RequestBin data into the request body.
  • 張貼到您的 Event Grid 觸發程序函式的 URL。Post to the URL of your Event Grid trigger function.
    • 2.x 中,使用下列模式:For 2.x use the following pattern:

      http://localhost:7071/runtime/webhooks/eventgrid?functionName={FUNCTION_NAME}
      
    • 用於 1.x:For 1.x use:

      http://localhost:7071/admin/extensions/EventGridExtensionConfig?functionName={FUNCTION_NAME}
      

functionName 參數必須是 FunctionName 屬性中指定的名稱。The functionName parameter must be the name specified in the FunctionName attribute.

下列螢幕擷取畫面顯示 Postman 中的標頭和要求本文:The following screenshots show the headers and request body in Postman:

Postman 中的標頭

Postman 中的要求本文

Event Grid 觸發程序函式會執行並顯示類似於下列範例的記錄:The Event Grid trigger function executes and shows logs similar to the following example:

Event Grid 觸發程序函式記錄的範例

使用 ngrok 進行本機測試Local testing with ngrok

在本機測試 Event Grid 觸發程序的另一種方式,是自動建立網際網路與您開發電腦之間的 HTTP 連線。Another way to test an Event Grid trigger locally is to automate the HTTP connection between the Internet and your development computer. 您可以在做之類的工具ngrok:You can do that with a tool like ngrok:

  1. 建立 ngrok 端點Create an ngrok endpoint.
  2. 執行 Event Grid 觸發程序函式Run the Event Grid trigger function.
  3. 建立會將事件傳送至 ngrok 端點的 Event Grid 訂用帳戶Create an Event Grid subscription that sends events to the ngrok endpoint.
  4. 觸發事件Trigger an event.

完成測試後,您可以藉由更新端點,在生產環境使用相同的訂用帳戶。When you're done testing, you can use the same subscription for production by updating the endpoint. 使用 az eventgrid event-subscription update Azure CLI 命令。Use the az eventgrid event-subscription update Azure CLI command.

建立 ngrok 端點Create an ngrok endpoint

ngrok 下載 ngrok.exe,並使用下列命令加以執行:Download ngrok.exe from ngrok, and run with the following command:

ngrok http -host-header=localhost 7071

此時必須使用 -host-header 參數,因為函式執行階段在 localhost 執行時預期會有來自 localhost 的要求。The -host-header parameter is needed because the functions runtime expects requests from localhost when it runs on localhost. 7071 是執行階段在本機執行時的預設連接埠號碼。7071 is the default port number when the runtime runs locally.

此命令會建立如下的輸出:The command creates output like the following:

Session Status                online
Version                       2.2.8
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://263db807.ngrok.io -> localhost:7071
Forwarding                    https://263db807.ngrok.io -> localhost:7071

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

您的 Event Grid 訂用帳戶將會使用 https://{subdomain}.ngrok.io URL。You'll use the https://{subdomain}.ngrok.io URL for your Event Grid subscription.

執行 Event Grid 觸發程序函式Run the Event Grid trigger function

Event Grid 不會以特殊方式處理 ngrok URL,因此,在訂用帳戶建立時,您的函式必須在本機執行。The ngrok URL doesn't get special handling by Event Grid, so your function must be running locally when the subscription is created. 若非如此,則不會傳送驗證回應,且訂用帳戶的建立將會失敗。If it isn't, the validation response doesn't get sent and the subscription creation fails.

建立訂用帳戶Create a subscription

建立您想要測試的 Event Grid 訂用帳戶類型,並為其提供您的 ngrok 端點。Create an Event Grid subscription of the type you want to test, and give it your ngrok endpoint.

將此端點模式使用於 Functions 2.x:Use this endpoint pattern for Functions 2.x:

https://{SUBDOMAIN}.ngrok.io/runtime/webhooks/eventgrid?functionName={FUNCTION_NAME}

將此端點模式使用於 Functions 1.x:Use this endpoint pattern for Functions 1.x:

https://{SUBDOMAIN}.ngrok.io/admin/extensions/EventGridExtensionConfig?functionName={FUNCTION_NAME}

{FUNCTION_NAME} 參數必須是 FunctionName 屬性中指定的名稱。The {FUNCTION_NAME} parameter must be the name specified in the FunctionName attribute.

以下是使用 Azure CLI 的範例:Here's an example using the Azure CLI:

az eventgrid event-subscription create --resource-id /subscriptions/aeb4b7cb-b7cb-b7cb-b7cb-b7cbb6607f30/resourceGroups/eg0122/providers/Microsoft.Storage/storageAccounts/egblobstor0122 --name egblobsub0126 --endpoint https://263db807.ngrok.io/runtime/webhooks/eventgrid?functionName=EventGridTrigger

如需如何建立訂用帳戶的相關資訊,請參閱本文前述的建立訂用帳戶For information about how to create a subscription, see Create a subscription earlier in this article.

觸發事件Trigger an event

觸發會對您的 ngrok 端點產生 HTTP 流量的事件。Trigger an event that will generate HTTP traffic to your ngrok endpoint. 例如,如果您已建立 Blob 儲存體訂用帳戶,請上傳或刪除 Blob。For example, if you created a blob storage subscription, upload or delete a blob.

Event Grid 觸發程序函式會執行並顯示類似於下列範例的記錄:The Event Grid trigger function executes and shows logs similar to the following example:

Event Grid 觸發程序函式記錄的範例

以 HTTP 觸發程序作為 Event Grid 觸發程序Use an HTTP trigger as an Event Grid trigger

接收到的 Event Grid 事件會是 HTTP 要求,因此您可以使用 HTTP 觸發程序來處理事件,而不使用 Event Grid 觸發程序。Event Grid events are received as HTTP requests, so you can handle events by using an HTTP trigger instead of an Event Grid trigger. 這麼做的可能原因之一,是對於叫用函式的端點 URL 想要有更充分的掌控。One possible reason for doing that is to get more control over the endpoint URL that invokes the function. 另一個原因是當您需要接收 CloudEvents 結構描述中的事件時。Another reason is when you need to receive events in the CloudEvents schema. 事件格線觸發程序目前不支援 CloudEvents 結構描述。Currently, the Event Grid trigger doesn't support the CloudEvents schema. 本節中的範例示範事件格線結構描述和 CloudEvents 結構描述的解決方案。The examples in this section show solutions for both Event Grid schema and CloudEvents schema.

如果您使用 HTTP 觸發程序,則必須撰寫程式碼來處理 Event Grid 觸發程序自動執行的作業:If you use an HTTP trigger, you have to write code for what the Event Grid trigger does automatically:

  • 將驗證回應傳送給訂用帳戶驗證要求Sends a validation response to a subscription validation request.
  • 為要求本文中包含的每個事件陣列元素分別叫用一次函式。Invokes the function once per element of the event array contained in the request body.

如需在本機叫用函式時或在 Azure 中執行函式時所使用的 URL 相關資訊,請參閱 HTTP 觸發程序繫結參考文件For information about the URL to use for invoking the function locally or when it runs in Azure, see the HTTP trigger binding reference documentation

事件格線結構描述Event Grid schema

HTTP 觸發程序的下列範例 C# 程式碼會模擬事件格線觸發程序的行為。The following sample C# code for an HTTP trigger simulates Event Grid trigger behavior. 使用此範例示範以事件格線結構描述傳送的事件。Use this example for events delivered in the Event Grid schema.

[FunctionName("HttpTrigger")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    var messages = await req.Content.ReadAsAsync<JArray>();

    // If the request is for subscription validation, send back the validation code.
    if (messages.Count > 0 && string.Equals((string)messages[0]["eventType"],
        "Microsoft.EventGrid.SubscriptionValidationEvent",
        System.StringComparison.OrdinalIgnoreCase))
    {
        log.LogInformation("Validate request received");
        return req.CreateResponse<object>(new
        {
            validationResponse = messages[0]["data"]["validationCode"]
        });
    }

    // The request is not for subscription validation, so it's for one or more events.
    foreach (JObject message in messages)
    {
        // Handle one event.
        EventGridEvent eventGridEvent = message.ToObject<EventGridEvent>();
        log.LogInformation($"Subject: {eventGridEvent.Subject}");
        log.LogInformation($"Time: {eventGridEvent.EventTime}");
        log.LogInformation($"Event data: {eventGridEvent.Data.ToString()}");
    }

    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 觸發程序的下列範例 JavaScript 程式碼會模擬事件格線觸發程序行為。The following sample JavaScript code for an HTTP trigger simulates Event Grid trigger behavior. 使用此範例示範以事件格線結構描述傳送的事件。Use this example for events delivered in the Event Grid schema.

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var messages = req.body;
    // If the request is for subscription validation, send back the validation code.
    if (messages.length > 0 && messages[0].eventType == "Microsoft.EventGrid.SubscriptionValidationEvent") {
        context.log('Validate request received');
        var code = messages[0].data.validationCode;
        context.res = { status: 200, body: { "ValidationResponse": code } };
    }
    else {
        // The request is not for subscription validation, so it's for one or more events.
        // Event Grid schema delivers events in an array.
        for (var i = 0; i < messages.length; i++) {
            // Handle one event.
            var message = messages[i];
            context.log('Subject: ' + message.subject);
            context.log('Time: ' + message.eventTime);
            context.log('Data: ' + JSON.stringify(message.data));
        }
    }
    context.done();
};

您的事件處理程式碼會透過 messages 陣列進入迴圈。Your event-handling code goes inside the loop through the messages array.

CloudEvents 結構描述CloudEvents schema

HTTP 觸發程序的下列範例 C# 程式碼會模擬事件格線觸發程序的行為。The following sample C# code for an HTTP trigger simulates Event Grid trigger behavior. 使用此範例示範以 CloudEvents 結構描述傳送的事件。Use this example for events delivered in the CloudEvents schema.

[FunctionName("HttpTrigger")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    var requestmessage = await req.Content.ReadAsStringAsync();
    var message = JToken.Parse(requestmessage);

    if (message.Type == JTokenType.Array)
    {
        // If the request is for subscription validation, send back the validation code.
        if (string.Equals((string)message[0]["eventType"],
        "Microsoft.EventGrid.SubscriptionValidationEvent",
        System.StringComparison.OrdinalIgnoreCase))
        {
            log.LogInformation("Validate request received");
            return req.CreateResponse<object>(new
            {
                validationResponse = message[0]["data"]["validationCode"]
            });
        }
    }
    else
    {
        // The request is not for subscription validation, so it's for an event.
        // CloudEvents schema delivers one event at a time.
        log.LogInformation($"Source: {message["source"]}");
        log.LogInformation($"Time: {message["eventTime"]}");
        log.LogInformation($"Event data: {message["data"].ToString()}");
    }

    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 觸發程序的下列範例 JavaScript 程式碼會模擬事件格線觸發程序行為。The following sample JavaScript code for an HTTP trigger simulates Event Grid trigger behavior. 使用此範例示範以 CloudEvents 結構描述傳送的事件。Use this example for events delivered in the CloudEvents schema.

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var message = req.body;
    // If the request is for subscription validation, send back the validation code.
    if (message.length > 0 && message[0].eventType == "Microsoft.EventGrid.SubscriptionValidationEvent") {
        context.log('Validate request received');
        var code = message[0].data.validationCode;
        context.res = { status: 200, body: { "ValidationResponse": code } };
    }
    else {
        // The request is not for subscription validation, so it's for an event.
        // CloudEvents schema delivers one event at a time.
        var event = JSON.parse(message);
        context.log('Source: ' + event.source);
        context.log('Time: ' + event.eventTime);
        context.log('Data: ' + JSON.stringify(event.data));
    }
    context.done();
};

後續步驟Next steps