How to create a WebPubSubServiceClient
with .NET and Azure Identity
This how-to guide shows you how to create a WebPubSubServiceClient
using Microsoft Entra ID in .NET.
Requirements
Install Azure.Identity from nuget.org.
dotnet add package Azure.Identity
Install Azure.Messaging.WebPubSub from nuget.org
dotnet add package Azure.Messaging.WebPubSub
If using DependencyInjection, install Microsoft.Extensions.Azure from nuget.org
dotnet add package Microsoft.Extensions.Azure
Sample codes
Create a
TokenCredential
with Azure Identity SDK.using Azure.Identity; namespace chatapp { public class Program { public static void Main(string[] args) { var credential = new DefaultAzureCredential(); } } }
credential
can be any class that inherits fromTokenCredential
class.- EnvironmentCredential
- ClientSecretCredential
- ClientCertificateCredential
- ManagedIdentityCredential
- VisualStudioCredential
- VisualStudioCodeCredential
- AzureCliCredential
To learn more, see Azure Identity client library for .NET
Then create a
client
withendpoint
,hub
, andcredential
.using Azure.Identity; using Azure.Messaging.WebPubSub; public class Program { public static void Main(string[] args) { var credential = new DefaultAzureCredential(); var client = new WebPubSubServiceClient(new Uri("<endpoint>"), "<hub>", credential); } }
Or inject it into
IServiceCollections
with ourBuilderExtensions
.using System; using Azure.Identity; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace chatapp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddAzureClients(builder => { var credential = new DefaultAzureCredential(); builder.AddWebPubSubServiceClient(new Uri("<endpoint>"), "<hub>", credential); }); } } }
Learn how to use this client, see Azure Web PubSub service client library for .NET