Blazor WebAssembly Tutorial for .NET 10: Build a C# App

Last updated: October 17, 2026 · Tested with .NET 10 (SDK 10.0.401, Microsoft.AspNetCore.Components.WebAssembly 10.0.12), Edge 155, Windows 11

Short answer: Blazor WebAssembly runs your C# in the browser on a .NET runtime compiled to WebAssembly. Create an app with dotnet new blazorwasm, write components in .razor files, call APIs with HttpClient and publish the output as static files. I built the task-tracker app below on .NET 10 and ran it in a real browser. The published app downloads 2.25 MB (Brotli) on first load. A cross-origin API call fails until the API sends CORS headers. Blocking on a task with .Result doesn’t deadlock: it throws PlatformNotSupportedException. Exact output for each is below.

What Blazor WebAssembly Is (and When to Pick It)

Blazor WebAssembly is the client-side hosting model of ASP.NET Core Blazor. The browser downloads the .NET runtime (dotnet.native.wasm), your app’s assemblies and the framework assemblies, then runs your components locally. UI events are handled in the browser, with no server round trip. Blazor Server does the opposite: components run on the server and UI diffs travel over a SignalR connection.

  • Pick Blazor WebAssembly for internal tools, dashboards and apps behind a login, where a one-time download is fine, you want cheap static hosting, or the app has to keep working offline (PWA).
  • Pick Blazor Server or a Blazor Web App with prerendering when first-page speed or search-engine visibility matters, or the client must never see your assemblies.
  • Pick React, Angular or Vue when your team is JavaScript-first or depends on their component ecosystems.

The .NET 10 Blazor Web App template lets you mix these per component (Server, WebAssembly or Auto render mode). The full comparison is in Blazor Server vs WebAssembly vs United. This tutorial uses the standalone WebAssembly template, which produces a pure client-side app.

Step 1: Create the App on .NET 10

dotnet new blazorwasm -o TaskTracker
cd TaskTracker
dotnet run

Open the URL printed in the console. The template assigns random ports per project; mine were http://localhost:5016 and https://localhost:7236, so don’t expect the old 5001. The .NET 10 project file looks like this:

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <OverrideHtmlAssetPlaceholders>true</OverrideHtmlAssetPlaceholders>
  </PropertyGroup>

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

</Project>

Two .NET 10 details that older tutorials don’t mention:

  • OverrideHtmlAssetPlaceholders lets the build rewrite wwwroot/index.html. The template’s script tag is <script src="_framework/blazor.webassembly#[.{fingerprint}].js">, and publish replaces the placeholder with a content hash (mine became blazor.webassembly.w3qd1tpl0e.js). Every framework file is fingerprinted the same way, so browsers can cache them safely.
  • There is no blazor.boot.json in the publish output any more. The boot configuration is inlined into dotnet.<hash>.js. If a deployment script or service worker of yours looks for blazor.boot.json, update it.

Program.cs is a normal .NET host builder. Here it is after Step 3, with a second HttpClient for the API:

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using TaskTracker;
using TaskTracker.Services;

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

// Default HttpClient: same origin as the app (wwwroot files such as sample-data/weather.json).
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

// API on a different origin: base address comes from wwwroot/appsettings.json.
var apiBase = builder.Configuration["ApiBaseUrl"] ?? "http://localhost:5280/";
builder.Services.AddScoped(sp => new TaskApiClient(new HttpClient { BaseAddress = new Uri(apiBase) }));

await builder.Build().RunAsync();

Step 2: Build an Interactive Component

The model, Models/TaskItem.cs:

namespace TaskTracker.Models;

public class TaskItem
{
    public Guid Id { get; set; }
    public required string Title { get; set; }
    public bool IsDone { get; set; }
}

The page, Pages/Tasks.razor. It adds, ticks and deletes tasks, and saves them to localStorage through JS interop, so they survive a reload:

@page "/tasks"
@using TaskTracker.Models
@inject IJSRuntime JS

<PageTitle>My Tasks</PageTitle>

<h1>Task Tracker</h1>

<div class="input-group mb-3">
    <input class="form-control" placeholder="What needs doing?"
           @bind="newTaskTitle" @bind:event="oninput" @onkeydown="HandleKeyDown" />
    <button class="btn btn-primary" disabled="@string.IsNullOrWhiteSpace(newTaskTitle)"
            @onclick="AddTaskAsync">Add</button>
</div>

@if (tasks.Count == 0)
{
    <p><em>No tasks yet. Add one above!</em></p>
}
else
{
    <ul class="list-group">
        @foreach (var task in tasks)
        {
            <li class="list-group-item d-flex align-items-center" @key="task.Id">
                <input type="checkbox" class="form-check-input me-2"
                       checked="@task.IsDone" @onchange="() => ToggleTaskAsync(task)" />
                <span style="@(task.IsDone ? "text-decoration: line-through" : null)">@task.Title</span>
                <button class="btn btn-sm btn-outline-danger ms-auto" @onclick="() => RemoveTaskAsync(task)">Delete</button>
            </li>
        }
    </ul>
    <p class="mt-2" id="remaining">@tasks.Count(t => !t.IsDone) remaining</p>
}

@code {
    private List<TaskItem> tasks = [];
    private string newTaskTitle = string.Empty;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // localStorage is a browser API, so JS interop runs after the first render.
        if (!firstRender) return;
        var json = await JS.InvokeAsync<string?>("localStorage.getItem", "tasks");
        if (!string.IsNullOrEmpty(json))
        {
            tasks = System.Text.Json.JsonSerializer.Deserialize<List<TaskItem>>(json) ?? [];
            StateHasChanged(); // state changed outside an event handler
        }
    }

    private async Task AddTaskAsync()
    {
        if (string.IsNullOrWhiteSpace(newTaskTitle)) return;
        tasks.Add(new TaskItem { Id = Guid.NewGuid(), Title = newTaskTitle.Trim() });
        newTaskTitle = string.Empty;
        await SaveAsync();
    }

    private async Task ToggleTaskAsync(TaskItem task)
    {
        task.IsDone = !task.IsDone;
        await SaveAsync();
    }

    private async Task RemoveTaskAsync(TaskItem task)
    {
        tasks.Remove(task);
        await SaveAsync();
    }

    private async Task HandleKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter") await AddTaskAsync();
    }

    private Task SaveAsync() => JS.InvokeVoidAsync("localStorage.setItem", "tasks",
        System.Text.Json.JsonSerializer.Serialize(tasks)).AsTask();
}

I drove this page in headless Edge over the Chrome DevTools Protocol: typed two tasks, pressed Enter after each, ticked the first and reloaded the page. Output (IDs shortened):

after adding 2 and ticking 1: 1 remaining
localStorage: [{"Id":"4c0469bc-...","Title":"Write the post","IsDone":true},{"Id":"7b4812b1-...","Title":"Run the code","IsDone":false}]
after reload: 1 remaining Write the post (done), Run the code

What’s doing the work:

  • @bind with @bind:event="oninput" updates newTaskTitle on every keystroke, which is why the Add button enables while you type.
  • @onclick, @onchange and @onkeydown call C# methods. Blazor re-renders the component after each handler, so no StateHasChanged() is needed there.
  • The one StateHasChanged() call is in OnAfterRenderAsync, because that’s state changing outside an event handler.
  • @key="task.Id" makes Blazor match list items by ID. Without it, deleting the first task can leave its checkbox state on the item that slides up into its place.
  • The JS interop calls (localStorage.getItem/setItem) need no JavaScript file: IJSRuntime calls the browser function by name. I load in OnAfterRenderAsync rather than OnInitializedAsync. Both work in a standalone WebAssembly app, but if you later move the component into a Blazor Web App with prerendering, interop during the server prerender fails, and OnAfterRenderAsync only runs in the browser.

Step 3: Call an API (and Hit the CORS Error)

A typed client in Services/TaskApiClient.cs. On WebAssembly, HttpClient is implemented on top of the browser’s fetch:

using System.Net.Http.Json;
using TaskTracker.Models;

namespace TaskTracker.Services;

public class TaskApiClient(HttpClient http)
{
    public async Task<List<TaskItem>> GetTasksAsync(CancellationToken ct = default)
        => await http.GetFromJsonAsync<List<TaskItem>>("api/tasks", ct) ?? [];

    public async Task<TaskItem?> CreateTaskAsync(TaskItem task, CancellationToken ct = default)
    {
        var response = await http.PostAsJsonAsync("api/tasks", task, ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<TaskItem>(ct);
    }
}

The page, Pages/ApiTasks.razor:

@page "/api-tasks"
@using TaskTracker.Models
@using TaskTracker.Services
@inject TaskApiClient Api

<h1>Tasks from the API</h1>

@if (error is not null)
{
    <p class="text-danger" id="error">@error</p>
}
else if (isLoading)
{
    <p><em>Loading...</em></p>
}
else
{
    <ul id="api-list">
        @foreach (var task in tasks)
        {
            <li @key="task.Id">@task.Title</li>
        }
    </ul>
}

@code {
    private List<TaskItem> tasks = [];
    private bool isLoading = true;
    private string? error;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            tasks = await Api.GetTasksAsync();
        }
        catch (HttpRequestException ex)
        {
            error = $"Failed to load tasks: {ex.Message}";
            Console.Error.WriteLine(error);
        }
        finally
        {
            isLoading = false;
        }
    }
}

The API is a minimal API in a separate project on http://localhost:5280, so it’s a different origin from the app on port 5016. With CORS off, curl and Postman get the JSON fine, but the browser doesn’t. This is what the page and the browser console showed:

page shows: Failed to load tasks: TypeError: Failed to fetch

[javascript.error] Access to fetch at 'http://localhost:5280/api/tasks' from origin 'http://localhost:5016'
  has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
[network.error] Failed to load resource: net::ERR_FAILED

Note what .NET gives you: an HttpRequestException whose message is only TypeError: Failed to fetch. The reason (CORS) appears only in the browser console, so always check DevTools when an API call fails in Blazor WebAssembly. The fix belongs in the API, not in the Blazor app:

var builder = WebApplication.CreateBuilder(args);

var allowCors = Environment.GetEnvironmentVariable("ALLOW_CORS") == "1";
if (allowCors)
{
    builder.Services.AddCors(o => o.AddPolicy("blazor", p => p
        .WithOrigins("http://localhost:5016", "https://localhost:7236")
        .AllowAnyHeader()
        .AllowAnyMethod()));
}

var app = builder.Build();
if (allowCors) app.UseCors("blazor");

var tasks = new List<TaskDto>
{
    new(Guid.NewGuid(), "Write the Blazor post", false),
    new(Guid.NewGuid(), "Measure the publish size", true),
};

app.MapGet("/api/tasks", () => tasks);
app.MapPost("/api/tasks", (TaskDto t) => { tasks.Add(t); return Results.Created($"/api/tasks/{t.Id}", t); });

app.Run("http://localhost:5280");

record TaskDto(Guid Id, string Title, bool IsDone);

With ALLOW_CORS=1 the response carries Access-Control-Allow-Origin: http://localhost:5016 and the page lists both tasks:

page shows: Write the Blazor post
Measure the publish size

List exact origins with WithOrigins. AllowAnyOrigin() can’t be combined with credentials, and it opens your API to every site. For more on HttpClient lifetimes, timeouts and retries (mostly relevant on the server side), see HttpClient in .NET 10. For the API itself, see Minimal APIs.

How Big Is a Blazor WebAssembly App? Measured

I published the app with dotnet publish -c Release, served wwwroot from a static server that sends the precompressed .br files, and counted the bytes the browser transferred for _framework/ with an empty cache:

BuildFramework requestsTransferred (Brotli)
Default publish412.25 MB
-p:InvariantGlobalization=true402.10 MB

The largest files were dotnet.native.wasm (954 KiB), System.Private.CoreLib.wasm (504 KiB), the ICU culture data icudt_EFIGS.dat (141 KiB) and System.Text.Json.wasm (127 KiB). Things worth knowing:

  • Compression on the host matters most. The same 41 files are 2.78 MB with gzip and 6.98 MB uncompressed. Publish generates .br and .gz files next to each asset; make sure your host or CDN actually serves them.
  • The publish folder overstates the download. _framework holds three ICU files (EFIGS, CJK, no-CJK), but an English browser loaded only the EFIGS one.
  • Invariant globalization saved 150 KB here. Use it only if you don’t need culture-specific formatting or sorting: dates, numbers and string comparison all fall back to invariant culture.
  • JSON serialization pulled in 127 KiB on its own. Every NuGet package you add shows up in this list, so check _framework after adding one. For serializer trade-offs, see System.Text.Json vs Newtonsoft.

Gotcha: .Result and .Wait() Throw Instead of Deadlocking

Many articles, including the first version of this one, say that blocking on a task in Blazor WebAssembly deadlocks the app. On .NET 10 it doesn’t: it fails right away. Pages/BlockingDemo.razor:

@page "/blocking"
@inject HttpClient Http

<button id="block" @onclick="Block">Block with .Result</button>
<p id="result">@result</p>

@code {
    private string result = "";

    private void Block()
    {
        try
        {
            // Anti-pattern: synchronously waiting on a task in the browser.
            result = Http.GetStringAsync("sample-data/weather.json").Result[..20];
        }
        catch (Exception ex)
        {
            result = $"{ex.GetType().FullName}: {ex.Message}";
            Console.Error.WriteLine(result);
        }
    }
}

Clicking the button in the browser printed:

System.PlatformNotSupportedException: Cannot wait on monitors on this runtime.

The default WebAssembly runtime is single-threaded, so a blocking wait could never complete, and the runtime throws instead of hanging. The fix is to make the handler async Task and await the call. Look for this exception in your logs when porting code that uses .Result, .Wait(), GetAwaiter().GetResult() or Task.WaitAll from a server app.

Production Checklist

  1. Never put secrets in the app. Every assembly in _framework can be downloaded and decompiled. Keep keys and connection strings on the API, authenticate users with OpenID Connect (Microsoft.AspNetCore.Components.WebAssembly.Authentication) and authorize on the server. See JWT authentication in ASP.NET Core.
  2. Lazy-load large feature assemblies. Mark them in the project file and load them on navigation with LazyAssemblyLoader. Since .NET 8 the item uses the .wasm file name: <BlazorWebAssemblyLazyLoad Include="Reports.wasm" />. Older posts show .dll, which no longer matches.
  3. AOT compilation is opt-in, so measure it. <RunAOTCompilation>true</RunAOTCompilation> needs the wasm-tools workload (dotnet workload install wasm-tools). It speeds up CPU-heavy code, but publishing takes much longer and the download gets bigger. I didn’t benchmark it for this app, which has no CPU-heavy code. Turn it on only if profiling shows the interpreter is your bottleneck.
  4. Use EventCallback<T> for child-to-parent parameters instead of Action<T>. It re-renders the parent and supports async handlers.
  5. Dispose subscriptions. Components that subscribe to events or start timers should implement IDisposable or IAsyncDisposable. A single-page app lives a long time, so leaks add up.
  6. Use [JSImport]/[JSExport] (System.Runtime.InteropServices.JavaScript, available since .NET 7) when interop is hot and IJSRuntime‘s JSON marshalling becomes a cost.

FAQ

Does a Blazor WebAssembly app need a server?
Not to run the UI. The publish output is static files you can host on Azure Static Web Apps, GitHub Pages, Cloudflare Pages or S3. Data still needs an API, and that API needs CORS if it lives on another origin.

Is Blazor WebAssembly good for SEO?
A standalone WebAssembly app sends an almost empty index.html and renders in the browser. For public pages that should rank, use a Blazor Web App with prerendering so the HTML arrives server-rendered.

How large is the download?
2.25 MB with Brotli for the app in this tutorial on .NET 10, cached by the browser after the first visit thanks to fingerprinted file names. Your number grows with each package you reference.

Can Blazor WebAssembly talk to a database directly?
No. Code in the browser can’t safely hold a connection string. Put EF Core behind an ASP.NET Core API and call it with HttpClient.

Conclusion

Blazor WebAssembly on .NET 10 is a solid way to build client-side apps in C#: the template is lean, framework files are fingerprinted, and a small app is about 2.25 MB on the wire. The two surprises I hit were CORS errors that .NET reports only as TypeError: Failed to fetch, and .Result throwing PlatformNotSupportedException. Both are easy once you know where to look. Next, add authentication and deploy the static files. Deploying the API is covered in Deploy ASP.NET Core to Azure App Service.

References: Blazor hosting models · Enable CORS in ASP.NET Core · Lazy load assemblies in Blazor WebAssembly · Blazor JavaScript interop · WebAssembly build tools and AOT

This article is part of the ASP.NET Core tutorials guide (APIs, security, observability and deployment).

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *