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

1k views Asked by At

Surfing the web leads me to think that the default Wasm app employs bad practice by newing a HttpClient instead of using IHttpClientFactory. So how do I do it properly?

FetchData.razor uses HttpClient this way:

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

And the dependency injection is setup in Program.cs with this line:

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

It seems it shouldn't be too hard to make the change, but I can't figure it out.

1

There are 1 answers

0
Hal Heinrich On BEST ANSWER

After a lot of web surfing and trial & error, I got this to work.

First I installed the Microsoft.Extensions.Http NuGet package.

Then I changed the code in Program.cs to this:

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

And FetchData.razor to this:

@*@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");
    }

If my solution has flaws, I'd appreciate hearing about them.