Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active September 25, 2024 09:43
Show Gist options
  • Save xiaomi7732/50da8f8f739a1ed05b2fde667cd9ba9f to your computer and use it in GitHub Desktop.
Save xiaomi7732/50da8f8f739a1ed05b2fde667cd9ba9f to your computer and use it in GitHub Desktop.
Use HttpFactory for multiple HttpClients in Blazor WASM

Use HttpFactory for multiple HttpClients in Blazor WASM

Description

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.

Details

  1. NuGet package

    Package with factory classes to be added:

        <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
  2. 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.

  3. Inject IHttpClientFactory to use named HttpClient

    @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!");
                }
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment