用于 .NET 的 Azure 事件网格库

将简单的基于 HTTP 的事件处理与 Azure 事件网格配合使用,开发事件驱动型应用程序,以便侦听并响应来自 Azure 服务和自定义源的事件。

详细了解 Azure 事件网格,通过 Azure Blob 存储事件教程来入门。

客户端 SDK

使用 Azure 事件网格客户端 SDK 创建事件、进行身份验证以及发布到主题。

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包

Visual Studio 包管理器

Install-Package Microsoft.Azure.EventGrid

.NET Core CLI

dotnet add package Microsoft.Azure.EventGrid 

发布事件

以下代码通过 Azure 进行身份验证,然后将自定义类型(在此示例中为 Contoso.Items.ItemsReceivedEvent)的 EventGridEvent 事件的 List 发布到某个主题。 在示例中使用的主题密钥和终结点地址可以从 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.cn/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;
}

使用事件

此代码片段使用多种事件,包括一个自定义事件 Contoso.Items.ItemsReceived,以及其他 Azure 服务(例如 Blob 存储)触发的事件。

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;
    }
}

管理 SDK

使用管理 SDK 创建、更新或删除事件网格实例、主题和订阅。

直接从 Visual Studio 包管理器控制台或使用 .NET Core CLI 安装 NuGet 包

Visual Studio 包管理器

Install-Package Microsoft.Azure.Management.EventGrid

.NET Core CLI

dotnet add package Microsoft.Azure.Management.EventGrid

了解详细信息