在默认 Visual Studio Blazor WebAssembly 应用程序中,您将如何使用 IHttpClientFactory 创建 HttpClient?

In the default Visual Studio Blazor WebAssembly app, how would you create the HttpClient using IHttpClientFactory?

网上冲浪让我认为默认的 Wasm 应用程序通过新建 HttpClient 而不是使用 IHttpClientFactory 采用了不好的做法。那么我该如何正确操作呢?

FetchData.razor 以这种方式使用 HttpClient:

@inject HttpClient Http
...
protected override async Task OnInitializedAsync()
{
    forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}

依赖注入是在 Program.cs 中用这一行设置的:

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

看来改起来应该不难,就是想不通。

经过大量的网上冲浪和反复试验后,我终于成功了。

首先我安装了 Microsoft.Extensions.Http NuGet 包。

然后我将 Program.cs 中的代码更改为:

//builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 
builder.Services.AddHttpClient("Wf", httpClient =>
{
    httpClient.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
});

和FetchData.razor到这个:

@*@inject HttpClient Http*@
@inject IHttpClientFactory _httpClientFactory
...
    protected override async Task OnInitializedAsync()
    {
        var Http = _httpClientFactory.CreateClient("Wf");
        forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
    }

如果我的解决方案有缺陷,我将不胜感激。