Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 41 ยท State and Dependency Injection

Calling APIs from Blazor with HttpClient

Fetch and send JSON from Blazor components with HttpClient, typed clients and IHttpClientFactory, and handle loading, errors and cancellation in the UI.

Almost every real Blazor app talks to a web API: a list of products, a login endpoint, a save button. In .NET that job belongs to HttpClient, and in Blazor it is injected like any other service. The interesting part is not the call itself but the UI around it: showing a loading state, surviving errors, cancelling when the user leaves the page and keeping the HTTP details out of your components.

The Razor snippets here are real Blazor code and read-only. The runnable examples use a stand-in: a fake HttpMessageHandler that answers requests from memory, so the real HttpClient runs on the site without any network. This is also exactly how you unit-test code that uses HttpClient.

HttpClient in the two hosting models

On Blazor WebAssembly, HttpClient is backed by the browser's fetch. That means browser rules apply: cross-origin calls need CORS headers from the API, and you cannot set some headers. On Blazor Server and server-side render modes, HttpClient is the normal .NET client running on the server, with no CORS restrictions and direct access to internal network addresses.

You register it in Program.cs:

C#
// WebAssembly: a client whose base address is the site itself
builder.Services.AddScoped(sp => new HttpClient
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});

// Server (or any host): the factory-based registration
builder.Services.AddHttpClient();

Relative URLs such as weather then resolve against BaseAddress.

Reading JSON in a component

The System.Net.Http.Json extension methods remove the boilerplate:

RAZOR
@page "/products"
@inject HttpClient Http

<h1>Products</h1>

@if (products is null)
{
    <p>Loading...</p>
}
else
{
    <ul>
        @foreach (var p in products)
        {
            <li>@p.Name: @p.Price.ToString("C")</li>
        }
    </ul>
}

@code {
    private Product[]? products;

    protected override async Task OnInitializedAsync()
    {
        products = await Http.GetFromJsonAsync<Product[]>("api/products");
    }

    private record Product(int Id, string Name, decimal Price);
}

null means "not loaded yet". Blazor renders the loading text first, then re-renders when the awaited call finishes. This works because OnInitializedAsync returns a Task and the framework re-renders after it completes (see Component Lifecycle).

Writing data is just as short:

C#
var response = await Http.PostAsJsonAsync("api/products", newProduct);
response.EnsureSuccessStatusCode();
var created = await response.Content.ReadFromJsonAsync<Product>();

A runnable client with a fake server

The next example uses a real HttpClient and a real System.Net.Http.Json call, but the "server" is a handler that returns JSON from memory.

C# Stand-in: HttpClient with an in-memory handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that a 404 does not throw. HttpClient only throws for network failures (HttpRequestException); an error status is a normal response you must inspect, or turn into an exception with EnsureSuccessStatusCode(). GetFromJsonAsync is different: it calls EnsureSuccessStatusCode for you, so a 404 becomes an HttpRequestException.

Loading, error and empty states

A robust component models the three outcomes explicitly:

RAZOR
@if (loading)
{
    <p>Loading...</p>
}
else if (error is not null)
{
    <p class="error">@error <button @onclick="Load">Retry</button></p>
}
else if (products.Count == 0)
{
    <p>No products yet.</p>
}
else
{
    <ProductTable Items="products" />
}

@code {
    private List<Product> products = [];
    private bool loading;
    private string? error;

    protected override Task OnInitializedAsync() => Load();

    private async Task Load()
    {
        loading = true;
        error = null;
        try
        {
            products = await Http.GetFromJsonAsync<List<Product>>("api/products") ?? [];
        }
        catch (HttpRequestException ex)
        {
            error = $"Could not load products ({ex.StatusCode?.ToString() ?? "network error"}).";
        }
        finally
        {
            loading = false;
        }
    }
}

The finally block guarantees the spinner disappears. The same shape works for save buttons: disable the button while a request runs so users cannot double-submit.

Typed clients and IHttpClientFactory

Calling Http.GetFromJsonAsync("api/products") from twenty components scatters URLs and error handling everywhere. A typed client wraps one API behind a class with meaningful methods:

C#
public class ProductsApi(HttpClient http)
{
    public Task<List<Product>?> GetAllAsync(CancellationToken ct = default) =>
        http.GetFromJsonAsync<List<Product>>("api/products", ct);

    public async Task<Product> CreateAsync(Product product, CancellationToken ct = default)
    {
        var response = await http.PostAsJsonAsync("api/products", product, ct);
        response.EnsureSuccessStatusCode();
        return (await response.Content.ReadFromJsonAsync<Product>(ct))!;
    }
}

// Program.cs
builder.Services.AddHttpClient<ProductsApi>(c => c.BaseAddress = new Uri("https://shop.example/"));

Components inject ProductsApi, not HttpClient. IHttpClientFactory manages the underlying connections so you avoid both socket exhaustion and stale DNS, and you can add handlers (retry, logging, an authorization header) in one place.

Cancellation

If the user navigates away while a request is running, the component is disposed but the request keeps going. Pass a CancellationToken and cancel it in Dispose:

RAZOR
@implements IDisposable

@code {
    private readonly CancellationTokenSource cts = new();

    protected override async Task OnInitializedAsync()
    {
        products = await Api.GetAllAsync(cts.Token);
    }

    public void Dispose() => cts.Cancel();
}

A cancelled call throws OperationCanceledException; catch it quietly, because it is not an error the user needs to see.

A typed client with retry, runnable

C# Stand-in: typed client that handles failure and cancellation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Creating new HttpClient() in every component. Inject it, or use a typed client from the factory.
  • Forgetting CORS in WebAssembly. A call to another origin fails in the browser even when the API works in Postman.
  • No loading or error state. Users see an empty page and assume the app is broken.
  • Ignoring non-success codes from GetAsync/PostAsync: they do not throw.
  • Exposing secrets. In WebAssembly everything runs in the browser, so never put an API key in a client-side call; route through your own server.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does HttpClient do when the server answers 404?

    An error status is a normal response. GetFromJsonAsync and EnsureSuccessStatusCode turn it into an exception.
  2. 2. Why is a typed client better than injecting HttpClient everywhere?

    A typed client gives components meaningful methods and a single place to change the API details.
  3. 3. Which extra rule applies to HttpClient in Blazor WebAssembly?

    In WebAssembly the client uses the browser's fetch, so same-origin policy and CORS apply.
  4. 4. What should a component do with an in-flight request when it is disposed?

    Cancel in Dispose so the work stops, and catch OperationCanceledException quietly.

Summary

  • Inject HttpClient; in WebAssembly it uses the browser, on the server it is the normal .NET client.
  • GetFromJsonAsync, PostAsJsonAsync and ReadFromJsonAsync handle JSON in one line.
  • Model loading, error and empty states, and always reset the loading flag in finally.
  • Wrap each API in a typed client registered with AddHttpClient<T>.
  • Pass a CancellationToken and cancel on dispose; a fake HttpMessageHandler makes this testable.

Next: JavaScript Interop Basics