如何使用 .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
範例程式碼
TokenCredential
使用 Azure 身分識別 SDK 建立 。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 身分識別客戶端連結庫
然後使用、
hub
建立credential
endpoint
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); } }
或者,將它
IServiceCollections
插入我們的BuilderExtensions
。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 服務客戶端連結庫