如何在C#中为Azure Blob存储创建Event Grid事件订阅
用C#创建Azure Blob存储Event Grid系统主题订阅(推送到Service Bus)
步骤1:安装必要的NuGet包
确保你的.NET Core项目中安装以下包:
Azure.ResourceManager.EventGrid:用于管理Event Grid资源Azure.Identity:用于Azure服务认证
步骤2:编写实现代码
以下是完整的实现示例,通过Azure资源管理器SDK创建订阅,指定Blob事件过滤规则,并将事件推送到Service Bus:
using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.EventGrid; using Azure.ResourceManager.EventGrid.Models; // 初始化资源管理器客户端 var armClient = new ArmClient(new DefaultAzureCredential()); // 替换为你的Azure订阅ID、资源组名称、Event Grid系统主题名称 string subscriptionId = "your-subscription-id"; string resourceGroupName = "your-resource-group-name"; string systemTopicName = "your-system-topic-name"; // 获取系统主题资源 var subscription = armClient.GetSubscriptionResource(new Azure.Core.ResourceIdentifier($"/subscriptions/{subscriptionId}")); var resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName); var systemTopic = await resourceGroup.GetEventGridSystemTopicAsync(systemTopicName); // 定义订阅名称 string eventSubscriptionName = "blob-events-to-servicebus-subscription"; // 配置Service Bus端点(替换为你的Service Bus队列/主题的资源ID) string serviceBusEndpointResourceId = "/subscriptions/{subscription-id}/resourceGroups/{rg-name}/providers/Microsoft.ServiceBus/namespaces/{sb-namespace}/queues/{queue-name}"; var serviceBusEndpoint = new ServiceBusQueueEventSubscriptionDestination(serviceBusEndpointResourceId); // 指定要监听的Blob事件类型 var eventTypes = new List<string> { "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted", "Microsoft.Storage.BlobRenamed" }; // 创建事件订阅参数 var eventSubscriptionData = new EventGridSubscriptionData { Destination = serviceBusEndpoint, Filter = new EventSubscriptionFilter { IncludedEventTypes = eventTypes, // 可选:添加Blob路径前缀过滤,比如只监听特定容器下的Blob // SubjectBeginsWith = "/blobServices/default/containers/your-container-name" } }; // 创建事件订阅 await systemTopic.Value.GetEventGridSystemTopicEventSubscriptions().CreateOrUpdateAsync( WaitUntil.Completed, eventSubscriptionName, eventSubscriptionData); Console.WriteLine("Event Grid订阅创建成功");
关键说明
- 认证方式:示例中使用
DefaultAzureCredential,它会自动从环境变量、Azure CLI、托管标识等渠道获取认证信息,适配本地开发和生产环境。 - 事件类型:Blob存储的三类目标事件分别对应:
Microsoft.Storage.BlobCreated(Blob创建/上传)、Microsoft.Storage.BlobDeleted(Blob删除)、Microsoft.Storage.BlobRenamed(Blob重命名)。 - Service Bus端点:需传入Service Bus队列或主题的完整资源ID,可在Azure门户的Service Bus资源「属性」页获取。
- 过滤规则:通过
SubjectBeginsWith可添加容器路径过滤,仅监听指定容器内的Blob事件,减少无效事件推送。
注意事项
- 运行代码的身份(本地开发为你的Azure账号,生产环境为托管标识)需拥有EventGrid EventSubscriptions Contributor和Service Bus Data Sender权限。
- 系统主题必须已关联目标Blob存储账户,否则无法监听Blob事件。
内容的提问来源于stack exchange,提问作者Arshad Badar Khan
相关产品推荐
相关产品推荐

