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

如何在C#中获取Azure Event Hub的连接字符串?

在C#中获取指定名称Azure Event Hub的连接字符串

要通过C#获取指定Event Hub的连接字符串,需要借助Azure Event Hubs管理库结合Azure身份验证来实现,具体步骤如下:

1. 安装必要的NuGet包

需要安装两个核心包:Azure.ResourceManager.EventHubs用于管理Event Hub资源,Azure.Identity用于完成Azure AD身份验证。

在Package Manager Console执行:

Install-Package Azure.ResourceManager.EventHubs
Install-Package Azure.Identity

或通过.NET CLI执行:

dotnet add package Azure.ResourceManager.EventHubs
dotnet add package Azure.Identity

2. 编写查询代码

以下是完整实现代码,需替换代码中的订阅ID、资源组名称、Event Hub命名空间名称及目标Event Hub名称:

using Azure.Identity;
using Azure.ResourceManager.EventHubs;
using Azure.ResourceManager.EventHubs.Models;
using Azure.ResourceManager.Resources;

// 替换为你的订阅ID
string subscriptionId = "your-subscription-id";
// 替换为你的资源组名称
string resourceGroupName = "your-resource-group-name";
// 替换为Event Hub所在的命名空间名称
string namespaceName = "your-eventhub-namespace-name";
// 替换为要查询的Event Hub名称
string eventHubName = "your-target-eventhub-name";

// 初始化资源管理器客户端
ArmClient armClient = new ArmClient(new DefaultAzureCredential());

// 获取订阅资源
SubscriptionResource subscription = await armClient.GetSubscriptionResource(new ResourceIdentifier($"/subscriptions/{subscriptionId}")).GetAsync();

// 获取目标资源组
ResourceGroupResource resourceGroup = await subscription.GetResourceGroupAsync(resourceGroupName);

// 获取Event Hub命名空间资源
EventHubNamespaceResource namespaceResource = await resourceGroup.GetEventHubNamespaceAsync(namespaceName);

// 获取指定名称的Event Hub资源
EventHubResource eventHub = await namespaceResource.GetEventHubAsync(eventHubName);

// 查询该Event Hub下的所有授权规则并获取连接字符串
EventHubAuthorizationRuleCollection authRules = eventHub.GetEventHubAuthorizationRules();
await foreach (EventHubAuthorizationRuleResource rule in authRules.GetAllAsync())
{
    // 获取包含全部权限的连接字符串
    EventHubConnectionString connectionString = await rule.GetConnectionStringAsync(EventHubAccessRights.Listen | EventHubAccessRights.Send | EventHubAccessRights.Manage);
    Console.WriteLine($"授权规则 {rule.Data.Name} 的主连接字符串:{connectionString.PrimaryConnectionString}");
}

关键说明

  • 身份验证:示例使用DefaultAzureCredential,它会自动从环境变量、Azure CLI、Visual Studio等渠道获取认证凭据,适配本地开发与生产环境。
  • 指定授权规则:如果不需要遍历所有规则,可直接通过规则名称获取,比如默认的RootManageSharedAccessKey:
EventHubAuthorizationRuleResource rule = await eventHub.GetEventHubAuthorizationRuleAsync("RootManageSharedAccessKey");
EventHubConnectionString connectionString = await rule.GetConnectionStringAsync(EventHubAccessRights.Listen | EventHubAccessRights.Send);
  • 权限控制:EventHubAccessRights枚举可按需组合权限,比如仅需要发送权限就用EventHubAccessRights.Send。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:01:11