如何使用 .NET 和 Azure 标识创建 WebPubSubServiceClient
本操作指南演示如何在 .NET 中使用 Microsoft Entra ID 创建 WebPubSubServiceClient
。
要求
从 nuget.org 安装 Azure.Identity。
dotnet add package Azure.Identity
从 nuget.org 安装 Azure.Messaging.WebPubSub
dotnet add package Azure.Messaging.WebPubSub
如果使用 DependencyInjection,请从 nuget.org 安装 Microsoft.Extensions.Azure
dotnet add package Microsoft.Extensions.Azure
示例代码
使用 Azure 标识 SDK 创建
TokenCredential
。using Azure.Identity; namespace chatapp { public class Program { public static void Main(string[] args) { var credential = new DefaultAzureCredential(); } } }
credential
可以是继承自TokenCredential
类的任何类。- EnvironmentCredential
- ClientSecretCredential
- ClientCertificateCredential
- ManagedIdentityCredential
- VisualStudioCredential
- VisualStudioCodeCredential
- AzureCliCredential
若要了解详细信息,请参阅适用于 .NET 的 Azure 标识客户端库
然后,使用
endpoint
、hub
和credential
创建client
。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); } }
或者使用我们的
BuilderExtensions
将其注入IServiceCollections
。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); }); } } }
了解如何使用此客户端,请参阅适用于 .NET 的 Azure Web PubSub 服务客户端库