在网上冲浪让我认为默认的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。剃刀:
@*@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");
}
如果我的解决方案有缺陷,我很高兴听到它们。