HttpClient Factory pattern allows multiple named http client for various backend. This is a note about how to use it in Blazor WASM (.NET 6).
Short version: Same as in a Web API.
-
NuGet package
Package with factory classes to be added:
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
-
Register named HttpClients
builder.Services.AddHttpClient(HttpClientName.Local, (_, c) => { c.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress); }); builder.Services.AddHttpClient(HttpClientName.Backend, (_, c) => { c.BaseAddress = new Uri("https://localhost:7280"); });
In that example, we registered 2 named http client - Local and Backend.
HttpClientName
is a simple class that holds constant strings for HttpClient names. -
Inject
IHttpClientFactory
to use namedHttpClient
@page "/login" @inject IHttpClientFactory _httpClientFactory; // Injecting IHttpClientFactory ... @code { public LoginCredential LoginCredential { get; } = new LoginCredential(); public async Task LoginCommandAsync() { // Create httpClient for use, dispose at the end. // Notice, although the HttpClient object will be disposed, the handler won't. using (HttpClient httpClient = _httpClientFactory.CreateClient(HttpClientName.Backend)) { HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync<LoginCredential>(new Uri("/token", UriKind.Relative), LoginCredential); if (responseMessage.IsSuccessStatusCode) { Console.WriteLine("Login succeeded!"); } } } }