Compartir a través de

如何使用 .NET 和 Azure 标识创建 WebPubSubServiceClient

本操作指南演示如何在 .NET 中使用 Microsoft Entra ID 创建 WebPubSubServiceClient

要求

示例代码

  1. 使用 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 标识客户端库

  2. 然后,使用 endpointhubcredential 创建 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 服务客户端库

完整示例