使用C#创建Azure Event Grid系统主题与订阅(类似Service Bus)
使用C#代码创建并配置Azure Event Grid系统主题
必要依赖
首先安装Azure资源管理器Event Grid的NuGet包:
Install-Package Azure.ResourceManager.EventGrid
或通过.NET CLI安装:
dotnet add package Azure.ResourceManager.EventGrid
核心代码示例
以下代码展示如何创建系统主题并配置事件订阅(以存储账户作为事件源为例):
using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.EventGrid; using Azure.ResourceManager.EventGrid.Models; using System; // 初始化ArmClient,使用默认凭据(本地开发可通过Azure CLI、Visual Studio等方式登录) var armClient = new ArmClient(new DefaultAzureCredential()); // 替换为实际的订阅ID、资源组名 var subscriptionId = Guid.Parse("你的订阅ID"); var resourceGroupName = "你的资源组名"; var resourceGroup = armClient.GetResourceGroupResource(new Azure.Core.ResourceIdentifier($"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}")); // 1. 创建系统主题 var systemTopicName = "demo-storage-system-topic"; // 替换为事件源的资源ID(示例为存储账户) var sourceResourceId = "/subscriptions/{订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.Storage/storageAccounts/{存储账户名}"; var systemTopicData = new SystemTopicData() { Source = sourceResourceId, TopicType = "Microsoft.Storage.StorageAccounts" // 对应存储账户的主题类型,不同服务类型对应不同值 }; var systemTopicOperation = await resourceGroup.GetSystemTopics().CreateOrUpdateAsync(Azure.WaitUntil.Completed, systemTopicName, systemTopicData); var systemTopic = systemTopicOperation.Value; Console.WriteLine($"系统主题 {systemTopicName} 创建完成,ID: {systemTopic.Id}"); // 2. 为系统主题添加事件订阅(示例:订阅到Service Bus队列) var eventSubscriptionName = "demo-system-topic-subscription"; var serviceBusQueueEndpoint = new ServiceBusQueueEventSubscriptionDestination() { ResourceId = "/subscriptions/{订阅ID}/resourceGroups/{资源组名}/providers/Microsoft.ServiceBus/namespaces/{ServiceBus命名空间名}/queues/{队列名}" }; var eventSubscriptionData = new EventSubscriptionData() { Destination = serviceBusQueueEndpoint, // 可选:过滤特定事件类型,比如仅订阅Blob创建事件 Filter = new EventSubscriptionFilter() { IncludedEventTypes = { "Microsoft.Storage.BlobCreated" } } }; var eventSubscriptionOperation = await systemTopic.GetEventSubscriptions().CreateOrUpdateAsync(Azure.WaitUntil.Completed, eventSubscriptionName, eventSubscriptionData); var eventSubscription = eventSubscriptionOperation.Value; Console.WriteLine($"事件订阅 {eventSubscriptionName} 创建完成");
关键说明
- 主题类型(TopicType):不同Azure服务对应不同的主题类型,比如Service Bus对应
Microsoft.ServiceBus.Namespaces、Event Hub对应Microsoft.EventHub.Namespaces,需根据事件源服务查询对应值。 - 权限要求:运行代码的身份需拥有目标资源组的
Event Grid Contributor或Contributor角色权限,确保能创建系统主题和事件订阅。 - 凭据方式:示例使用
DefaultAzureCredential,支持本地开发环境的多种登录方式,生产环境可使用托管身份或服务主体。
内容的提问来源于stack exchange,提问作者Arshad Badar Khan
相关产品推荐
相关产品推荐

