How to Get Azure Event Hub Connection String in C#?

1.3k Views Asked by At

Given a Event Hub Name, how can I get connection string in C#? I googled a bit, but nothing useful found so far. Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Using AAD authentication for an EventHub

var credential = new DefaultAzureCredential();
// or use 
// var credential = new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret");

EventHubProducerClient producerClient = new EventHubProducerClient(txtNamespace.Text, txtEventHub.Text, credential
var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, txtNamespace.Text, txtEventHub.Text, credential)

Full example and docs

Acquiring the Connection Strings of configured Access Policies

You can use these two Nuget packages:

Then you can use the resource group name and the eventhub name to retrieve the connection string. You will need to iterate the subscriptions and resource groups if you don't have this information.

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.EventHubs;


ArmClient client = new ArmClient(new DefaultAzureCredential()); 
// Or use
// ArmClient client = new ArmClient(new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret"));

var subscription = await client.GetDefaultSubscriptionAsync();
var resourceGroup = await subscription.GetResourceGroupAsync("myresourcegroup");
var eventhubNamespace = await resourceGroup.Value.GetEventHubsNamespaceAsync("namespacename");
var rules = eventhubNamespace.Value.GetEventHubsNamespaceAuthorizationRules();
foreach (var rule in rules)
{
    var keys = await rule.GetKeysAsync();
    Console.WriteLine(keys.Value.PrimaryConnectionString);
    Console.WriteLine(keys.Value.SecondaryConnectionString);
}
0
On

Not sure if this is what you mean, but if you want to access an Event Hub through C# you need to provide the EH connection string into your code. This can be retrieved by adding a Shared access policy for the Event hub that you are trying to access.

connection string for EH

Edit: If you are trying to actually create the connection string yourself you could follow this sample where you create the SAS-token yourself. But you would still need to provide the Primary key that is set on the policy from Azure.