您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

用于 .NET 的 Azure 事件网格库Azure Event Grid libraries for .NET

将简单的基于 HTTP 的事件处理与 Azure 事件网格配合使用,开发事件驱动型应用程序,以便侦听并响应来自 Azure 服务和自定义源的事件。Build event-driven applications that listen and react to events from Azure services and custom sources using simple HTTP-based event handling with Azure Event Grid.

详细了解 Azure 事件网格,通过 Azure Blob 存储事件教程来入门。Learn more about Azure Event Grid and get started with the Azure Blob storage event tutorial.

客户端 SDKClient SDK

使用 Azure 事件网格客户端 SDK 创建事件、进行身份验证以及发布到主题。Create events, authenticate, and post to topics using the Azure Event Grid Client SDK.

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.

Visual Studio 包管理器Visual Studio Package Manager

Install-Package Microsoft.Azure.EventGrid

.NET Core CLI.NET Core CLI

dotnet add package Microsoft.Azure.EventGrid 

发布事件Publish events

以下代码通过 Azure 进行身份验证,然后将自定义类型(在此示例中为 Contoso.Items.ItemsReceivedEvent)的 EventGridEvent 事件的 List 发布到某个主题。The following code authenticates with Azure and publishes a List of EventGridEvent events of a custom type (in this example, Contoso.Items.ItemsReceivedEvent ) to a topic. 在示例中使用的主题密钥和终结点地址可以从 Azure PowerShell 检索:The topic key and endpoint address used in the sample can be retrieved from Azure PowerShell:

$endpoint = (Get-AzureRmEventGridTopic -ResourceGroupName gridResourceGroup -Name <topic-name>).Endpoint
$keys = Get-AzureRmEventGridTopicKey -ResourceGroupName gridResourceGroup -Name <topic-name>
string topicEndpoint = "https://<topic-name>.<region>-1.eventgrid.azure.net/api/events";
string topicKey = "<topic-key>";
string topicHostname = new Uri(topicEndpoint).Host;

TopicCredentials topicCredentials = new TopicCredentials(topicKey);
EventGridClient client = new EventGridClient(topicCredentials);

client.PublishEventsAsync(topicHostname, GetEventsList()).GetAwaiter().GetResult();
Console.Write("Published events to Event Grid.");

static IList<EventGridEvent> GetEventsList()
{
    List<EventGridEvent> eventsList = new List<EventGridEvent>();
    for (int i = 0; i < 1; i++)
    {
        eventsList.Add(new EventGridEvent()
        {
            Id = Guid.NewGuid().ToString(),
            EventType = "Contoso.Items.ItemReceivedEvent",
            Data = new ContosoItemReceivedEventData()
            {
                ItemUri = "ContosoSuperItemUri"
            },

            EventTime = DateTime.Now,
            Subject = "Door1",
            DataVersion = "2.0"
        });
    }
    return eventsList;
}

使用事件Consume events

此代码片段使用多种事件,包括一个自定义事件 Contoso.Items.ItemsReceived,以及其他 Azure 服务(例如 Blob 存储)触发的事件。This snippet consumes events, including a custom event Contoso.Items.ItemsReceived as well as events triggered from other Azure services, such as Blob Storage.

string response = string.Empty;
string requestContent = await req.Content.ReadAsStringAsync();

EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();

// Optionally add one or more custom event type mappings
eventGridSubscriber.AddOrUpdateCustomEventMapping("Contoso.Items.ItemReceived", typeof(ContosoItemReceivedEventData));

var events = eventGridSubscriber.DeserializeEventGridEvents(requestContent);            
 
foreach (EventGridEvent receivedEvent in events)
{
    if (receivedEvent.Data is SubscriptionValidationEventData)
    {
        SubscriptionValidationEventData eventData = (SubscriptionValidationEventData)receivedEvent.Data;
        log.Info($"Got SubscriptionValidation event data, validationCode: {eventData.ValidationCode},  validationUrl: {eventData.ValidationUrl}, topic: {eventGridEvent.Topic}");
        // Handle subscription validation
    }
    else if (receivedEvent.Data is StorageBlobCreatedEventData)
    {
        StorageBlobCreatedEventData eventData = (StorageBlobCreatedEventData)receivedEvent.Data;
        log.Info($"Got BlobCreated event data, blob URI {eventData.Url}");
        // Handle StorageBlobCreatedEventData
    }
    else if (receivedEvent.Data is ContosoItemReceivedEventData)
    {
        ContosoItemReceivedEventData eventData = (ContosoItemReceivedEventData)receivedEvent.Data;
    }
}

管理 SDKManagement SDK

使用管理 SDK 创建、更新或删除事件网格实例、主题和订阅。Create, update, or delete Event Grid instances, topics, and subscriptions with the management SDK.

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.

Visual Studio 包管理器Visual Studio Package Manager

Install-Package Microsoft.Azure.Management.EventGrid

.NET Core CLI.NET Core CLI

dotnet add package Microsoft.Azure.Management.EventGrid

了解详细信息Learn more