You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Microsoft.Azure.EventGrid 1.1.0-preview的EventGridClient创建ServiceClientCredentials

解决EventGridClient构造函数的ServiceClientCredentials创建问题

嘿,我刚好对这个旧预览版的Event Grid SDK有点印象,帮你梳理下怎么弄!

对于Microsoft.Azure.EventGrid 1.1.0-preview这个版本,你不需要用AzureCredentialsFactory来创建凭证,因为Event Grid主题的认证是基于主题访问密钥的,官方提供了专门的TopicCredentials类来处理这个场景,它就是ServiceClientCredentials的实现类。

具体步骤和代码示例:

  1. 引用必要的命名空间
using Microsoft.Azure.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
  1. 创建TopicCredentials并初始化EventGridClient
    你需要先从Azure门户获取Event Grid主题的访问密钥,然后用它实例化TopicCredentials:
// 替换成你的Event Grid主题访问密钥
string topicAccessKey = "your-topic-access-key";
var credentials = new TopicCredentials(topicAccessKey);

// 初始化EventGridClient
var eventGridClient = new EventGridClient(credentials);
  1. 构造并发布EventGridEvent
    接下来就可以创建事件列表,调用PublishEventsAsync方法发布到指定的主题端点了:
// 构造事件
var events = new List<EventGridEvent>
{
    new EventGridEvent(
        id: Guid.NewGuid().ToString(),
        subject: "demo/subject",
        data: new { Content = "测试Event Grid事件" },
        eventType: "Demo.CustomEvent",
        eventTime: DateTime.UtcNow,
        dataVersion: "1.0"
    )
};

// 替换成你的Event Grid主题端点(格式:https://{topic-name}.{region}.eventgrid.azure.net/api/events)
string topicEndpoint = "https://your-topic-name.eastus-2.eventgrid.azure.net/api/events";

// 发布事件
await eventGridClient.PublishEventsAsync(new Uri(topicEndpoint), events);

额外提醒:

这个1.1.0-preview版本是比较早期的预览版,现在Azure官方推荐使用更稳定的Azure.Messaging.EventGrid SDK(新的Azure SDK范式),如果项目允许的话,建议升级到新版本,用法会更简洁直观。不过如果必须使用这个旧版本,上面的代码完全可以正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:53:33