快速入门:使用 Azure 门户和事件网格将自定义事件路由到 Web 终结点Quickstart: Route custom events to web endpoint with the Azure portal and Event Grid

Azure 事件网格是针对云的事件处理服务。Azure Event Grid is an eventing service for the cloud. 在本文中,将使用 Azure 门户创建一个自定义主题,然后订阅该自定义主题,再触发可查看结果的事件。In this article, you use the Azure portal to create a custom topic, subscribe to the custom topic, and trigger the event to view the result. 通常,你会将事件发送到处理事件数据并执行操作的终结点。Typically, you send events to an endpoint that processes the event data and takes actions. 但是,为了简化本文,你将事件发送到收集并显示消息的 Web 应用。However, to simplify this article, you send the events to a web app that collects and displays the messages.


如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

启用事件网格资源提供程序Enable Event Grid resource provider

如果以前未在 Azure 订阅中使用过事件网格,则可能需要注册事件网格资源提供程序。If you haven't previously used Event Grid in your Azure subscription, you may need to register the Event Grid resource provider.

在 Azure 门户中:In the Azure portal:

  1. 选择 订阅Select Subscriptions.
  2. 选择要用于事件网格的订阅。Select the subscription you're using for Event Grid.
  3. 在“设置”下,选择“资源提供程序”。Under Settings, select Resource providers.
  4. 找到 Microsoft.EventGridFind Microsoft.EventGrid.
  5. 如果尚未注册,请选择“注册”。If not registered, select Register.

完成注册可能需要一些时间。It may take a moment for the registration to finish. 选择“刷新”可更新状态。Select Refresh to update the status. 当“状态”为“已注册”后,即可继续。When Status is Registered, you're ready to continue.

创建自定义主题Create a custom topic

事件网格主题提供用户定义的终结点,可向其发布事件。An event grid topic provides a user-defined endpoint that you post your events to.

  1. 登录到 Azure 门户Sign in to Azure portal.

  2. 在主题的搜索栏中,键入“事件网格主题”,然后从下拉列表中选择“事件网格主题” 。In the search bar at the topic, type Event Grid Topics, and then select Event Grid Topics from the drop down list.


  3. 在“事件网格主题”页上的工具栏中选择“添加”。 On the Event Grid Topics page, select + Add on the toolbar.


  4. 在“创建主题”页上执行以下步骤:On the Create Topic page, follow these steps:

    1. 选择 Azure 订阅Select your Azure subscription.

    2. 选择现有的资源组,或者选择“新建”并输入 资源组名称Select an existing resource group or select Create new, and enter a name for the resource group.

    3. 为自定义主题提供唯一的 名称Provide a unique name for the custom topic. 主题名称必须唯一,因为它由 DNS 条目表示。The topic name must be unique because it's represented by a DNS entry. 请不要使用图中所示的名称。Don't use the name shown in the image. 而是创建自己的名称 - 它必须介于 3 到 50 个字符之间,并且只包含值 a-z、A-Z、0-9 和“-”。Instead, create your own name - it must be between 3-50 characters and contain only values a-z, A-Z, 0-9, and "-".

    4. 选择事件网格主题的 位置Select a location for the event grid topic.

    5. 在页面底部选择“查看 + 创建”。Select Review + create at the bottom of the page.


    6. 在“创建主题”页的“查看 + 创建”选项卡上,选择“创建” 。On the Review + create tab of the Create topic page, select Create.


  5. 部署成功后,在搜索栏中再次键入“事件网格主题”,然后像之前一样从下拉列表中选择“事件网格主题” 。After the deployment succeeds, type Event Grid Topics in the search bar again, and select Event Grid Topics from the drop-down list as you did before.

  6. 选择从列表中创建的主题。Select the topic you created from the list.


  7. 此时会显示主题的“事件网格主题”页。You see the Event Grid Topic page for your topic. 请将此页保持打开状态,Keep this page open. 稍后在本快速入门中需要使用此页。You use it later in the quickstart.


创建消息终结点Create a message endpoint

在为自定义主题创建订阅之前,请先创建事件消息的终结点。Before you create a subscription for the custom topic, create an endpoint for the event message. 通常情况下,终结点基于事件数据执行操作。Typically, the endpoint takes actions based on the event data. 为了简化此快速入门,将部署用于显示事件消息的预建的 Web 应用To simplify this quickstart, you 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.

  1. 在项目页中,选择“部署到 Azure”以将解决方案部署到订阅。In the article page, 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 Aquent.

  2. 部署可能需要几分钟才能完成。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

    如果部署失败,请查看错误消息。If the deployment fails, check the error message. 这是因为网站名称已被占用。It may be because the web site name is already taken. 再次部署模板,然后为网站选择其他名称。Deploy the template again and choose a different name for the site.

  3. 查看站点,但是尚未有事件发布到它。You see the site but no events have been posted to it yet.


订阅自定义主题Subscribe to custom topic

订阅事件网格主题,以告知事件网格要跟踪哪些事件,以及要将事件发送到何处。You subscribe to an event grid topic to tell Event Grid which events you want to track, and where to send the events.

  1. 现在,请在自定义主题的“事件网格主题”页上的工具栏中,选择“+ 事件订阅”。 Now, on the Event Grid Topic page for your custom topic, select + Event Subscription on the toolbar.


  2. 在“创建事件订阅”页上执行以下步骤:On the Create Event Subscription page, follow these steps:

    1. 输入事件订阅的“名称”。Enter a name for the event subscription.

    2. 对于“终结点类型”,请选择“Web Hook”。 Select Web Hook for the Endpoint type.

    3. 选择“选择终结点”。Choose Select an endpoint.


    4. 对于 Webhook 终结点,请提供你的 Web 应用的 URL,并将 api/updates 添加到主页 URL。For the web hook endpoint, provide the URL of your web app and add api/updates to the home page URL. 选择“确认所选内容”。Select Confirm Selection.

      提供终结点 URL

    5. 返回“创建事件订阅”页,选择“创建”。 Back on the Create Event Subscription page, select Create.

  3. 再次查看 Web 应用,并注意现已向该应用发送了订阅验证事件。View your web app again, and notice that a subscription validation event has been sent to it. 选择眼睛图标以展开事件数据。Select the eye icon to expand the event data. 事件网格发送验证事件,以便终结点可以验证它是否想要接收事件数据。Event Grid sends the validation event so the endpoint can verify that it wants to receive event data. Web 应用包含用于验证订阅的代码。The web app includes code to validate the subscription.


向主题发送事件Send an event to your topic

现在,让我们触发一个事件,看事件网格如何将消息分发到终结点。Now, let's trigger an event to see how Event Grid distributes the message to your endpoint. 使用 Azure CLI 或 PowerShell 向自定义主题发送测试性事件。Use either Azure CLI or PowerShell to send a test event to your custom topic. 通常情况下,应用程序或 Azure 服务会发送事件数据。Typically, an application or Azure service would send the event data.

第一个示例使用 Azure CLI。The first example uses Azure CLI. 它获取自定义主题的 URL 和密钥,以及示例事件数据。It gets the URL and key for the custom topic, and sample event data. 将自定义主题名称用于 <topic name>Use your custom topic name for <topic name>. 它将创建示例事件数据。It creates sample event data. JSON 的 data 元素是事件的有效负载。The data element of the JSON is the payload of your event. 可以将任何格式正确的 JSON 置于此字段中。Any well-formed JSON can go in this field. 也可将主题字段用于高级路由和筛选。You can also use the subject field for advanced routing and filtering. CURL 是发送 HTTP 请求的实用工具。CURL is a utility that sends HTTP requests.

Azure CLIAzure CLI

  1. 运行以下命令以获取主题的 终结点:复制并粘贴该命令后,更新 主题名称资源组名称,然后运行该命令。Run the following command to get the endpoint for the topic: After you copy and paste the command, update the topic name and resource group name before you run the command. 将把示例事件发布到此主题终结点。You will publish sample events to this topic endpoint.

    endpoint=$(az eventgrid topic show --name <topic name> -g <resource group name> --query "endpoint" --output tsv)
  2. 运行以下命令以获取自定义主题的 密钥:复制并粘贴该命令后,更新 主题名称资源组名称,然后运行该命令。Run the following command to get the key for the custom topic: After you copy and paste the command, update the topic name and resource group name before you run the command. 这是事件网格主题的主密钥。This is the primary key of the Event Grid topic. 要从 Azure 门户获取此密钥,请切换到“事件网格主题”页的“访问密钥”选项卡 。To get this key from the Azure portal, switch to the Access keys tab of the Event Grid Topic page. 要将事件发布到自定义主题,需要访问密钥。To be able post an event to a custom topic, you need the access key.

    key=$(az eventgrid topic key list --name <topic name> -g <resource group name> --query "key1" --output tsv)
  3. 复制以下包含事件定义的语句,然后按 ENTERCopy the following statement with the event definition, and press ENTER.

    event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/motorcycles", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "make": "Ducati", "model": "Monster"},"dataVersion": "1.0"} ]'
  4. 运行以下 Curl 命令以发布事件:在命令中,aeg-sas-key 标头设置为之前获得的访问密钥。Run the following Curl command to post the event: In the command, aeg-sas-key header is set to the access key you got earlier.

    curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint

Azure PowerShellAzure PowerShell

第二个示例使用 PowerShell,执行的步骤类似。The second example uses PowerShell to perform similar steps.

  1. 设置以下变量。Set the following variables. 复制并粘贴每个命令后,更新 主题名称资源组名称,然后运行该命令:After you copy and paste each command, update the topic name and resource group name before you run the command:

    资源组:Resource group:

    $resourceGroupName = "<resource group name>"

    事件网格主题名称:Event Grid topic name:

    $topicName = "<topic name>"
  2. 运行以下命令以获取主题的 终结点密钥Run the following commands to get the endpoint and the keys for the topic:

    $endpoint = (Get-AzEventGridTopic -ResourceGroupName $resourceGroupName -Name $topicName).Endpoint
    $keys = Get-AzEventGridTopicKey -ResourceGroupName $resourceGroupName -Name $topicName
  3. 准备事件。Prepare the event. 在 PowerShell 窗口中复制并运行这些语句。Copy and run the statements in the PowerShell window.

    $eventID = Get-Random 99999
    #Date format should be SortableDateTimePattern (ISO 8601)
    $eventDate = Get-Date -Format s
    #Construct body using Hashtable
    $htbody = @{
        id= $eventID
        eventTime= $eventDate   
        data= @{
    #Use ConvertTo-Json to convert event body from Hashtable to JSON Object
    #Append square brackets to the converted JSON payload since they are expected in the event's JSON payload syntax
    $body = "["+(ConvertTo-Json $htbody)+"]"
  4. 使用 Invoke-WebRequest cmdlet 发送事件。Use the Invoke-WebRequest cmdlet to send the event.

    Invoke-WebRequest -Uri $endpoint -Method POST -Body $body -Headers @{"aeg-sas-key" = $keys.Key1}

在事件网格查看器中验证Verify in the Event Grid Viewer

现已触发事件,并且事件网格已将消息发送到订阅时配置的终结点。You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing. 查看 Web 应用以查看刚刚发送的事件。View your web app to see the event you just sent.


清理资源Clean up resources

如果打算继续处理此事件,请不要清除本文中创建的资源。If you plan to continue working with this event, don't clean up the resources created in this article. 否则,请删除本文中创建的资源。Otherwise, delete the resources you created in this article.

  1. 在左侧菜单中选择“资源组”。Select Resource Groups on the left menu. 如果左侧菜单中未显示此选项,请在左侧菜单中选择“所有服务”,然后选择“资源组”。 If you don't see it on the left menu, select All Services on the left menu, and select Resource Groups.


  2. 选择资源组以启动“资源组”页。Select the resource group to launch the Resource Group page.

  3. 在工具栏中选择“删除资源组”。Select Delete resource group on the toolbar.

  4. 输入资源组的名称以确认删除,然后选择“删除”。Confirm deletion by entering the name of the resource group, and select Delete.

后续步骤Next steps

了解如何创建自定义主题和事件订阅后,请详细了解事件网格的功能:Now that you know how to create custom topics and event subscriptions, learn more about what Event Grid can help you do: