You need to enable JavaScript to run this app. Azure 如何以编程方式为存储账户创建事件订阅(C#)?
优惠活动
大模型
产品
解决方案
定价
更多

Azure 如何以编程方式为存储账户创建事件订阅(C#)?

批量为Azure存储账户创建BlobCreated事件订阅的C#实现方案

前置依赖准备

  • 需要引用的NuGet包:Azure.Identity、Azure.ResourceManager、Azure.ResourceManager.EventGrid
  • 运行权限要求:执行代码的身份(服务主体、托管身份、本地调试时的个人Azure账号)需对所有目标存储账户、关联的Azure Function拥有事件网格参与者权限,否则会触发403鉴权失败
  • 提前准备好固定参数:目标订阅ID、Function的事件触发完整URL、Function的系统托管身份资源ID、需要配置的存储账户范围(可以是固定列表,也可以按资源组批量筛选)

核心实现逻辑

整套实现完全基于Azure身份凭据鉴权,不需要存储账户密钥、Function访问密钥这类敏感信息,通过Azure Resource Manager客户端直接调用事件网格的配置接口,替代手动门户操作。运行时会自动跳过已存在的同规则命名的事件订阅,支持批量循环处理所有存储账户,不会因为重复配置报错。

可直接复用的代码示例

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.EventGrid;
using Azure.ResourceManager.EventGrid.Models;

// 自动适配不同运行环境的凭据:本地读az login/VS登录的身份,Azure环境自动取托管身份凭据
var credential = new DefaultAzureCredential();
var armClient = new ArmClient(credential);

// 固定配置项替换为你自己的实际值
string targetSubscriptionId = "你的目标订阅ID";
string storageAccountResourceGroup = "存储账户所在的资源组名";
string functionTriggerUrl = "https://你的函数应用名.azurewebsites.net/runtime/webhooks/EventGrid?functionName=你的监听函数名";
string functionResourceId = "/subscriptions/函数所在订阅ID/resourceGroups/函数资源组名/providers/Microsoft.Web/sites/你的函数应用名";

// 加载目标订阅下的资源
var subscription = await armClient.GetSubscriptions().GetAsync(targetSubscriptionId);

// 筛选出资源组下所有的存储账户(如果是你自己创建的固定账号列表,可以直接替换成ResourceIdentifier循环遍历)
var storageAccounts = await subscription.GetGenericResourcesAsync()
    .Where(res => res.ResourceType == "Microsoft.Storage/storageAccounts" 
                 && res.ResourceGroupName == storageAccountResourceGroup)
    .ToListAsync();

foreach (var storageAccount in storageAccounts)
{
    // 按固定规则生成事件订阅名,方便后续幂等判断
    string subscriptionName = $"{storageAccount.Name}-blobcreated-sub";
    // 跳过已存在的同名事件订阅,避免重复创建冲突
    bool isSubExist = storageAccount.GetEventGridSubscriptions()
        .Any(sub => sub.Data.Name == subscriptionName);
    if (isSubExist) continue;

    // 构造事件订阅配置:仅订阅BlobCreated事件,端点绑定你的Azure Function
    var subConfig = new EventGridSubscriptionData(
        destination: new AzureFunctionEventSubscriptionDestination(functionResourceId)
        {
            Uri = new Uri(functionTriggerUrl)
        })
    {
        IncludedEventTypes = new List<string> { "Microsoft.Storage.BlobCreated" },
        // 用托管身份做事件投递,不需要配置明文密钥
        DeliveryWithIdentity = new EventSubscriptionIdentity
        {
            Type = EventSubscriptionIdentityType.SystemAssigned
        },
        EventDeliverySchema = EventDeliverySchema.CloudEventsSchemaV10
    };

    // 执行创建操作,等待配置生效
    await storageAccount.GetEventGridSubscriptions()
        .CreateOrUpdateAsync(WaitUntil.Completed, subscriptionName, subConfig);
}

落地时的注意事项

  • 不要硬编码任何客户端密钥、租户密钥,全程走Azure AD身份鉴权,符合安全合规要求
  • 批量执行时建议增加异常捕获逻辑,单个存储账户配置失败时不要中断整个批量流程,把失败的账号ID和错误原因写到日志里方便排查
  • 严格限定IncludedEventTypes为实际需要的BlobCreated,不要全量订阅存储账户的所有事件类型,避免产生不必要的消息流量和费用
  • 如果你的存储账户分布在多个资源组,可以把资源筛选逻辑调整为遍历整个订阅下所有的存储账户,或者直接把你编程创建存储账户时记录的资源ID列表作为遍历源,减少全量扫描的耗时

内容的提问来源于stack exchange,提问作者user246392

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 02:06:05