Blazor · Data

HttpClient

Blazor WebAssembly components get their data from APIs over HTTP. HttpClient with the JSON helpers makes that a one-liner.

Intermediate 5 min Lesson 18 of 31Examples target .NET 9 Blazor Web App.
Before you start:Services
0/31 in Blazor
On this page · 5 min · Intermediate

Learning objectives#

  • Register an HttpClient for your API
  • Read and send JSON
  • Show loading and error states
  • Cancel requests when the user leaves

Explanation#

Register a typed client: builder.Services.AddHttpClient<ProductsClient>(c => c.BaseAddress = new Uri(apiUrl)).

System.Net.Http.Json adds GetFromJsonAsync<T>, PostAsJsonAsync, PutAsJsonAsync and DeleteAsync.

Always design for three states: loading, error and success.

In WebAssembly, HttpClient runs through the browser’s fetch, so the API must allow your origin with CORS.

Code example: A typed API client#

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


    public async Task<ProductDto> CreateAsync(ProductDto p)
    {
        var res = await http.PostAsJsonAsync("api/products", p);
        res.EnsureSuccessStatusCode();
        return (await res.Content.ReadFromJsonAsync<ProductDto>())!;
    }
}


// Program.cs (client)
builder.Services.AddHttpClient<ProductsClient>(c =>
    c.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));


// Component
// try { products = await Api.GetAllAsync(); }
// catch (HttpRequestException) { error = "Could not load products. Please try again."; }
Expected output
The component shows “Loading…”, then the list — or a friendly error if the API is down.

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. The typed client wraps all API calls in one class.
  2. GetFromJsonAsync downloads and deserialises in one step.
  3. EnsureSuccessStatusCode turns 4xx/5xx into exceptions.
  4. The component catches HttpRequestException and shows a message.

Real-world use case#

A Blazor WebAssembly front end calling the ASP.NET Core Web API built in the API track.

Common mistakes#

new HttpClient() in components

Creates connection problems and ignores configuration. Use DI-registered clients.

No error handling

Network failures happen. Show a retry option instead of a blank page.

Best practices#

  • Typed clients per API area
  • Handle loading, error and empty states
  • Pass CancellationToken
  • Attach tokens with a DelegatingHandler

Remember this#

AddHttpClient<TClient> + BaseAddress.

GetFromJsonAsync / PostAsJsonAsync.

Loading → error → data, every time.

Practice exercise#

Your task: Add DeleteAsync(int id) to ProductsClient.

Show solution
C# Illustrative
public async Task DeleteAsync(int id) =>
    (await http.DeleteAsync(
quot;api/products/
{id}")).EnsureSuccessStatusCode();

Mini quiz#

HttpClient quizMultiple choice Question 1 of 1

Which method sends an object as JSON in a POST request?

Score so far: 0/0

Want more? Practise all Blazor MCQs · Blazor interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.