Azure Functions 的 Azure 事件网格触发器Azure Event Grid trigger for Azure Functions

使用函数触发器来响应发送到事件网格主题的事件。Use the function trigger to respond to an event sent to an Event Grid topic.

若要了解设置和配置详细信息,请参阅概述For information on setup and configuration details, see the overview.

示例Example

如需 HTTP 触发器示例,请参阅将事件接收到 HTTP 终结点For an HTTP trigger example, see Receive events to an HTTP endpoint.

C#(2.x 及更高版本)C# (2.x and higher)

以下示例演示绑定到 EventGridEventC# 函数The following example shows a 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.

版本 1.xVersion 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));
        }
    }
}

特性和注释Attributes and annotations

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 中,可以为事件网格触发器使用以下参数类型:In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

  • JObject
  • string

在 Azure Functions 2.x 及更高版本中,还可以选择对事件网格触发器使用以下参数类型:In Azure Functions 2.x and higher, 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.

事件架构Event schema

事件网格事件的数据在 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.chinacloudapi.cn/{containername}/blobname.jpg",
    "sequencer": "000000000000272D000000000003D60F",
    "storageDiagnostics": {
      "batchId": "{guid}"
    }
  },
  "dataVersion": "",
  "metadataVersion": "1"
}]

显示的示例是包含一个元素的数组。The example shown is an array of one element. 事件网格始终发送一个数组,并可能在该数组中发送多个事件。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.

有关通用和特定于事件的属性的说明,请参阅事件网格文档中的事件属性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

若要开始接收事件网格 HTTP 请求,请创建一个事件网格订阅,用于指定可调用函数的终结点 URL。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 门户中使用事件网格触发器开发的函数,请选择“集成”,然后选择“事件网格触发器”并选择“创建事件网格订阅”。 For functions that you develop in the Azure portal with the Event Grid trigger, select Integration then choose the Event Grid Trigger and select Create Event Grid subscription.

在门户中将新事件订阅连接到触发器。

选择此链接时,门户将打开“创建事件订阅”页,其中已定义了当前触发器终结点。When you select this link, the portal opens the Create Event Subscription page with the current trigger endpoint already defined.

已定义函数终结点的“创建事件订阅”

有关如何使用 Azure 门户创建订阅的详细信息,请参阅事件网格文档中的创建自定义事件 - 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 (and higher) runtime

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

1.x 版运行时Version 1.x runtime

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

系统密钥是必须包含在事件网格触发器终结点 URL 中的授权密钥。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 (and higher) 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.chinacloudsites.cn/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.chinacloudsites.cn/admin/extensions/EventGridExtensionConfig?functionName=imageresizefunc&code=<key>

有关如何创建订阅的详细信息,请参阅 Blob 存储快速入门或其他事件网格快速入门。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 (and higher) runtime

http://{functionappname}.chinacloudsites.cn/admin/host/systemkeys/eventgrid_extension?code={masterkey}

1.x 版运行时Version 1.x runtime

http://{functionappname}.chinacloudsites.cn/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). 订阅事件网格主题时,请务必使用系统密钥。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

若要在本地测试事件网格触发器,必须获取从云中的来源位置传送到本地计算机的事件网格 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. 将请求手动发布到事件网格触发器函数的 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. 所部署的解决方案包括应用服务计划、应用服务 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.

Button to Deploy to Azure.

部署可能需要几分钟才能完成。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. 在 Web 浏览器中导航到 https://<your-site-name>.chinacloudsites.cnIn a web browser, navigate to: https://<your-site-name>.chinacloudsites.cn

查看站点,但是尚未有事件发布到它。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>.chinacloudsites.cn/api/updatesSo, the full URL is https://<your-site-name>.chinacloudsites.cn/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

在本地运行事件网格函数。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.
  • 发布到事件网格触发器函数的 URL。Post to the URL of your Event Grid trigger function.
    • 对于 2.x 及更高版本,请使用以下模式:For 2.x and higher 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 中的请求正文

事件网格触发器函数将会执行,并显示类似于以下示例的日志:The Event Grid trigger function executes and shows logs similar to the following example:

事件网格触发器函数日志示例

后续步骤Next steps