如何在 Blazor WebAssembly 中配置具有不同配置的多个 HttpClient 实例

How to configure multiple HttpClient instances with different configurations in Blazor WebAssembly

我正在尝试在 Blazor WASM 的 Program.cs class 中配置多个 API url。我没有在服务器端看到 AddHttpClient 扩展。想知道是否有人对此有替代解决方案?

这是我目前的情况:

var firstURI = new Uri("https://localhost:44340/");
var secondURI = new Uri("https://localhost:5001/");

void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
   where TClient : class where TImplementation : class, TClient
{
   builder.Services.AddHttpClient<TClient, TImplementation>(client =>
   {
       client.BaseAddress = apiBaseUrl;
   });
}

// HTTP services
RegisterTypedClient<IFirstService, FirstService>(firstURI);
RegisterTypedClient<ISecondService, SecondService>(secondURI);

这可以通过 Blazor 客户端完成。首先,在您的客户端包中,获取以下 nuget 包:Microsoft.Extensions.Http

然后,为这个例子创建两个 classes(通常你会使用一个接口,但是 class 本身应该在这里工作。我将演示两个不同的基地址使用所以你知道有区别。

   public class GoogleService
    {
        private readonly HttpClient httpClient;

        public GoogleService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

雅虎服务:

  public class YahooService
    {
        private readonly HttpClient httpClient;

        public YahooService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public string GetBaseUrl()
        {
            return httpClient.BaseAddress.ToString();
        }
    }

接下来,在您的客户端程序 Program.cs 中,您可以执行以下操作:

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddHttpClient<GoogleService>(client =>
            {
                client.BaseAddress = new Uri("https://google.com/");
            });

            builder.Services.AddHttpClient<YahooService>(client =>
            {
                client.BaseAddress = new Uri("https://yahoo.com/");
            });

            await builder.Build().RunAsync();
        }

接下来,你可以像这样将它们注入到你的前端,看到它们确实是两个不同的注入客户端:

@page "/"
@inject BlazorHttpClientTest.Client.Clients.GoogleService googleService;
@inject BlazorHttpClientTest.Client.Clients.YahooService yahooService;

<h1>Hello, world!</h1>

<label>Google Address:</label><label>@googleAddress</label>
<label>Yahoo Address:</label><label>@yahooAddress</label>

@code{
    string googleAddress;
    string yahooAddress;

    protected override void OnInitialized()
    {
        base.OnInitialized();

        googleAddress = googleService.GetBaseUrl();
        yahooAddress = yahooService.GetBaseUrl();

    }
}

就这样,你应该让它工作:

如果您需要我更深入地解释任何其他内容,请告诉我,否则,如果对您有用,请标记为已回答。