SharpRuneOpen playground

Loading JSON with HttpClient

Load a JSON file from wwwroot with HttpClient and GetFromJsonAsync, and show loading, empty, error and cancelled states.

  • 25 min
  • Read, predict, then run
Blazor WebAssembly project

In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.

At a glance

One page state for each outcome

RequestWhat happensPage state
Any file, while waitingthe first await rendersloading
trails.json4 objects become a Trail[]loaded: 4 trails, 28.4 km
empty.json[] gives 0 trailsthe empty message
missing.json404, so the call throwsfailed, with the error
Cancel tappedthe token is cancelledcancelled

GetFromJsonAsync resolves data/... against BaseAddress, throws HttpRequestException for an error status and reads camelCase JSON. Each outcome gets its own explicit state.

HttpClient inside the browser

Code in Blazor WebAssembly runs inside the browser, and the browser does not give it raw network sockets. The HttpClient you inject therefore uses a handler that sends each request with the browser's fetch API. Your C# looks the same as on a server, but browser rules apply. A request to another site needs that site to allow it with CORS headers. The browser manages cookies and some headers, and it may use its cache.

Program.cs registers the client with AddScoped and sets BaseAddress to HostEnvironment.BaseAddress. That value comes from the <base href> in index.html, resolved against the page address, and it always ends with a slash. WebAssembly apps have no request scopes, so a scoped service lives as long as the app, like a singleton. A relative path is combined with BaseAddress by the normal Uri rules. data/trails.json is appended to the base path. /data/trails.json starts at the site root and ignores the base path, which breaks an app hosted under a sub-path. The companion prints all three cases.

Files in wwwroot are published as static files next to the app. A request for data/trails.json returns the file. A request for a file that does not exist returns 404.

What GetFromJsonAsync does

GetFromJsonAsync<T> from System.Net.Http.Json combines three steps. It sends a GET request. It calls EnsureSuccessStatusCode, which throws HttpRequestException for any status outside 200 to 299; the exception has a StatusCode property and a message such as the 404 text you see in the app. Then it deserializes the body with System.Text.Json and returns T, or null if the JSON text is null.

The deserializer uses JsonSerializerDefaults.Web. Property names match without regard to case, the naming policy is camelCase, and numbers may be read from strings. That is how distanceKm fills DistanceKm in the Trail record, through its constructor. With the plain defaults, names must match exactly, so name never fills Name. The companion shows that difference: the second line prints null for the first name. JSON that is malformed, or whose shape does not fit T, throws JsonException. A key that does not match any property is ignored without an error, which is worth remembering when a value stays 0.

When you need more control, call GetAsync, inspect response.StatusCode yourself, and then call response.Content.ReadFromJsonAsync<T>(). That lets you treat 404 as an empty list, for example, instead of an error.

Rendering while the data is on its way

Blazor does not wait for OnInitializedAsync to finish before it shows the component. It renders once when the method first awaits something that is not complete, and again when the task finishes. Your markup must therefore make sense before the data exists. The Trails page keeps an explicit LoadState enum instead of guessing from a null array. A null array could mean not loaded yet, a failed request or a file that contained null. With the enum, loading, failed and cancelled are separate, and empty is a loaded result with no items.

Async event handlers render the same way. When you tap Reload, LoadAsync sets the state to Loading and then awaits. Blazor renders at that await, so the message and the disabled buttons appear at once, and it renders again when the handler completes. Disabling Reload and the File menu while a load runs means that two loads never overlap and write over each other's results.

Cancellation and disposal

Each load creates a CancellationTokenSource and passes its token to Task.Delay and to GetFromJsonAsync. Calling Cancel makes the awaited call throw OperationCanceledException; Task.Delay and HttpClient throw its subclass TaskCanceledException. In the browser, cancelling also aborts the fetch request. The page catches the exception and shows the cancelled state.

The component implements IDisposable. Blazor calls Dispose when the component leaves the render tree, for example when you navigate to another page or an if block stops rendering it. Without cancellation, the download would continue, the code after the await would run for a component nobody can see, and any work it does, such as writing to a shared service, would still happen. Calling StateHasChanged on a disposed component does nothing, but the wasted work remains.

HttpClient.Timeout, 100 seconds by default, also ends a request with TaskCanceledException. If you need to tell a user's cancel from a timeout, check token.IsCancellationRequested in the catch block.

Trace the HTTP Lab project

When the app starts, Program.cs registers the HttpClient and the Router shows the Trails page. OnInitializedAsync calls LoadAsync, which sets Loading and awaits the 800 ms delay. Blazor renders 'Loading data/trails.json…'. After the delay, GetFromJsonAsync requests the base address plus data/trails.json, receives four objects and returns a Trail array. The state becomes Loaded, and the list renders with the total from trails.Sum, 28.4 km.

Pick data/empty.json in the File menu. @bind writes the new path into source, and @bind:after calls LoadAsync. The array is empty, so the empty message appears. Pick data/missing.json and the request returns 404, EnsureSuccessStatusCode throws, and the failed state shows the exception message. Tap Reload and then Cancel, and Task.Delay throws, so the page shows the cancelled state.

The companion replays the same decisions in a console. It parses the JSON text from trails.json, runs the page's empty and failed rules on [], null and an object, and cancels a token before Task.Delay, which prints TaskCanceledException.

Common mistakes

Creating new HttpClient() inside a component loses the BaseAddress from Program.cs, and a relative path then fails with an exception about an invalid request URI. Inject the registered client instead. Putting the JSON file outside wwwroot means it is never served. A leading slash in the path breaks hosting under a sub-path. A request to another site without CORS headers fails with a network error, not a status code. Catching Exception for everything hides the difference between a 404, broken JSON and a cancel, so the user sees one vague message. Starting the load in OnAfterRenderAsync instead of OnInitializedAsync adds a render with no purpose. Forgetting the empty state shows an empty table with headers and no explanation.

Practice and review

Add a fifth trail to trails.json and write one key wrong, for example distance_km. Predict what the page shows before you run it: there is no error, and that trail has 0.0 km. Copy the new JSON into the companion and check it there too. Then add a file with broken JSON, add it to the File menu, and confirm that the JsonException branch shows its message. Next, replace GetFromJsonAsync with GetAsync and show 'No such file' for 404 while keeping the generic message for other errors. Finally, add a difficulty filter that works on the loaded array without a new request.

Key points
  • In WebAssembly, HttpClient uses the browser fetch API, so browser rules such as CORS apply.
  • BaseAddress plus a relative path without a leading slash finds files in wwwroot.
  • GetFromJsonAsync throws HttpRequestException for error status codes and JsonException for JSON that does not fit.
  • Render a clear state for loading, loaded, empty, failed and cancelled.
  • Cancel the request in Dispose so a component that left the screen stops its work.
Runs on this device: SharpRune compiles the Razor components and C# here and runs the app in Preview on .NET 9 WebAssembly. The same files run on a computer with the .NET 9 SDK and dotnet run.

Loading JSON with HttpClient — Blazor WebAssembly project

Run the project

  1. Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
  2. Wait for the trail list, then pick data/empty.json and data/missing.json in the File menu to see the empty and failed states.
  3. Tap Reload and then tap Cancel within the first second to see the cancelled state.
  4. Change a .razor file and tap Run again to rebuild.
  5. On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.

Download the project ↗

Project files

HttpLab.csprojDownload file ↗
HttpLab.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>HttpLab</AssemblyName>
    <RootNamespace>HttpLab</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>
Program.csDownload file ↗
Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using HttpLab;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// BaseAddress is the address the app was loaded from. A relative path such as
// "data/trails.json" then points at the file in wwwroot/data.
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

await builder.Build().RunAsync();
App.razorDownload file ↗
App.razor
@* The root component. This one-page app has no layout file,
   so the header sits here, above the Router. *@
<header class="bar">
    <span class="brand">HTTP Lab</span>
    <span class="tag">HttpClient + JSON</span>
</header>

<main>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <h1>Not found</h1>
            <p>There is no page at this address.</p>
        </NotFound>
    </Router>
</main>
_Imports.razorDownload file ↗
_Imports.razor
@using System.Globalization
@using System.Net.Http
@using System.Net.Http.Json
@using System.Text.Json
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using HttpLab
Pages/Trails.razorDownload file ↗
Pages/Trails.razor
@page "/"
@implements IDisposable
@inject HttpClient Http

<PageTitle>Trails</PageTitle>

<h1>Trails</h1>

<p class="muted">The page downloads a JSON file from wwwroot and shows what happened: loading, loaded, empty, failed or cancelled.</p>

<div class="field">
    <label for="source">File</label>
    @* @bind:after starts a new load each time you pick another file. *@
    <select id="source" @bind="source" @bind:after="LoadAsync" disabled="@isLoading">
        <option value="data/trails.json">data/trails.json</option>
        <option value="data/empty.json">data/empty.json (an empty array)</option>
        <option value="data/missing.json">data/missing.json (no such file)</option>
    </select>
</div>

<div class="row">
    <button class="primary" @onclick="LoadAsync" disabled="@isLoading">Reload</button>
    <button @onclick="Cancel" disabled="@(!isLoading)">Cancel</button>
</div>

@if (state == LoadState.Loading)
{
    <p class="status" role="status">Loading @source…</p>
}
else if (state == LoadState.Failed)
{
    <p class="status error" role="alert">Could not load @source. @error</p>
}
else if (state == LoadState.Cancelled)
{
    <p class="status" role="status">The request was cancelled. Tap Reload to try again.</p>
}
else if (trails is null || trails.Length == 0)
{
    <p class="status" role="status">The file loaded, but it has no trails.</p>
}
else
{
    <ul class="trails">
        @foreach (var trail in trails)
        {
            <li>
                <strong>@trail.Name</strong>
                <span>@trail.DistanceKm.ToString("0.0", CultureInfo.InvariantCulture) km · climb @trail.ClimbM m · @trail.Difficulty</span>
            </li>
        }
    </ul>
    <p class="muted">@trails.Length trails, @trails.Sum(t => t.DistanceKm).ToString("0.0", CultureInfo.InvariantCulture) km in total.</p>
}

@code {
    private enum LoadState { Loading, Loaded, Failed, Cancelled }

    private string source = "data/trails.json";
    private LoadState state = LoadState.Loading;
    private Trail[]? trails;
    private string? error;
    private CancellationTokenSource? cts;

    private bool isLoading => state == LoadState.Loading;

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

    private async Task LoadAsync()
    {
        // One CancellationTokenSource per load. Cancel and Dispose use it to stop this load.
        cts?.Dispose();
        cts = new CancellationTokenSource();
        var token = cts.Token;

        state = LoadState.Loading;
        trails = null;
        error = null;

        try
        {
            // A short pause so you can see the loading state and try Cancel.
            await Task.Delay(800, token);

            // GET the file, throw if the status is not 2xx, then deserialize the JSON body.
            trails = await Http.GetFromJsonAsync<Trail[]>(source, token);
            state = LoadState.Loaded;
        }
        catch (OperationCanceledException)
        {
            state = LoadState.Cancelled;
        }
        catch (HttpRequestException ex)
        {
            // The server answered 404 or another error status, or the network failed.
            error = ex.Message;
            state = LoadState.Failed;
        }
        catch (JsonException ex)
        {
            // The file exists, but its text does not fit Trail[].
            error = ex.Message;
            state = LoadState.Failed;
        }
    }

    private void Cancel() => cts?.Cancel();

    // Blazor calls Dispose when this component leaves the screen.
    // Cancelling stops a download that nobody would see.
    public void Dispose()
    {
        cts?.Cancel();
        cts?.Dispose();
    }

    // Property names match the JSON keys without regard to case: "distanceKm" fills DistanceKm.
    public sealed record Trail(string Name, double DistanceKm, int ClimbM, string Difficulty);
}
wwwroot/index.htmlDownload file ↗
wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTTP Lab</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="HttpLab.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
    --danger: #d32f2f;
    --ok: #2e7d32;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

a, button, input, label { touch-action: manipulation; }

select { touch-action: manipulation; }

.bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px 16px;
    padding: 12px 16px;
    background: #1f1b3a;
    color: #fff;
}

.brand {
    font-weight: 700;
    margin-right: auto;
}

.bar nav {
    display: flex;
    gap: 4px;
}

.bar nav a {
    color: #d9d4ff;
    text-decoration: none;
    padding: 6px 10px;
    border-radius: 8px;
}

.bar nav a.active {
    background: var(--accent);
    color: #fff;
}

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
    box-sizing: border-box;
}

h1 {
    font-size: 1.8rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 24px 0 8px;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

.muted {
    color: #777;
}

.row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]), select, textarea {
    font: inherit;
    color: inherit;
    background: transparent;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    box-sizing: border-box;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

button.link {
    border: none;
    color: var(--accent);
    padding: 4px 6px;
}

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

.tag {
    color: #d9d4ff;
    font-size: 0.9rem;
}

.field {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.field select {
    width: 100%;
    min-height: 42px;
}

.status {
    padding: 12px;
    border: 1px solid var(--line);
    border-radius: 10px;
}

.status.error {
    border-color: var(--danger);
    color: var(--danger);
    overflow-wrap: anywhere;
}

.trails {
    list-style: none;
    padding: 0;
    margin: 0;
}

.trails li {
    display: flex;
    flex-direction: column;
    padding: 10px 0;
    border-bottom: 1px solid var(--line);
}

.trails span {
    color: #777;
}
wwwroot/data/empty.jsonDownload file ↗
wwwroot/data/empty.json
[]
wwwroot/data/trails.jsonDownload file ↗
wwwroot/data/trails.json
[
  { "name": "Ridge Loop", "distanceKm": 8.4, "climbM": 420, "difficulty": "Moderate" },
  { "name": "River Walk", "distanceKm": 5.2, "climbM": 60, "difficulty": "Gentle" },
  { "name": "Pine Steps", "distanceKm": 3.1, "climbM": 310, "difficulty": "Steep" },
  { "name": "Lake Circuit", "distanceKm": 11.7, "climbM": 150, "difficulty": "Gentle" }
]

Expected result

The page shows 'Loading data/trails.json…' for about a second, then four trails with distance, climb and difficulty, and the line '4 trails, 28.4 km in total.' Picking data/empty.json shows 'The file loaded, but it has no trails.' Picking data/missing.json shows 'Could not load data/missing.json. Response status code does not indicate success: 404 (Not Found).' Tapping Cancel during a load shows 'The request was cancelled. Tap Reload to try again.' Reload and the File menu are disabled while a load is running, and Cancel is enabled only then.

The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

// The same text as wwwroot/data/trails.json in the Blazor project.
const string trailsJson = """
[
  { "name": "Ridge Loop", "distanceKm": 8.4, "climbM": 420, "difficulty": "Moderate" },
  { "name": "River Walk", "distanceKm": 5.2, "climbM": 60, "difficulty": "Gentle" },
  { "name": "Pine Steps", "distanceKm": 3.1, "climbM": 310, "difficulty": "Steep" },
  { "name": "Lake Circuit", "distanceKm": 11.7, "climbM": 150, "difficulty": "Gentle" }
]
""";

// 1. Where a relative path goes. BaseAddress ends with a slash in a Blazor app.
var baseAddress = new Uri("https://localhost:5001/");
var hosted = new Uri("https://example.com/apps/trails/");
Console.WriteLine(new Uri(baseAddress, "data/trails.json"));
Console.WriteLine(new Uri(hosted, "data/trails.json"));
Console.WriteLine(new Uri(hosted, "/data/trails.json"));

// 2. GetFromJsonAsync deserializes with the web defaults: camelCase keys match PascalCase properties.
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var trails = JsonSerializer.Deserialize<Trail[]>(trailsJson, web)!;
Console.WriteLine($"Web defaults: {trails.Length} trails, {trails.Sum(t => t.DistanceKm):0.0} km, first is {trails[0].Name}");

// The plain defaults compare names exactly, so "name" never fills Name.
var strict = JsonSerializer.Deserialize<Trail[]>(trailsJson)!;
Console.WriteLine($"Plain defaults: {strict.Length} trails, first name is {strict[0].Name ?? "null"}");

// 3. The same state decision as the page.
Console.WriteLine(Describe(trailsJson));
Console.WriteLine(Describe("[]"));
Console.WriteLine(Describe("null"));
Console.WriteLine(Describe("{ \"name\": \"Ridge Loop\" }"));

// 4. A token that is already cancelled stops the wait before any request starts.
using var cts = new CancellationTokenSource();
cts.Cancel();
try
{
    await Task.Delay(800, cts.Token);
}
catch (OperationCanceledException ex)
{
    Console.WriteLine($"Cancelled: {ex.GetType().Name}");
}

string Describe(string json)
{
    try
    {
        var items = JsonSerializer.Deserialize<Trail[]>(json, web);
        return items is null || items.Length == 0 ? "empty" : $"loaded {items.Length}";
    }
    catch (JsonException)
    {
        return "failed: the JSON does not fit Trail[]";
    }
}

public sealed record Trail(string Name, double DistanceKm, int ClimbM, string Difficulty);
Open C# practice

C# practice output

https://localhost:5001/data/trails.json
https://example.com/apps/trails/data/trails.json
https://example.com/data/trails.json
Web defaults: 4 trails, 28.4 km, first is Ridge Loop
Plain defaults: 4 trails, first name is null
loaded 4
empty
empty
failed: the JSON does not fit Trail[]
Cancelled: TaskCanceledException
Try this
Write the path without a leading slash, such as data/trails.json. A leading slash starts from the site root and drops any base path the app is hosted under.

Further reading