Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

Data access in the browser

WebAssembly and Auto pages run in the browser, which has no connection to the database. The page stays the same, and a second store calls your API for it.

The client store and its endpoints

The page still asks the interface. A second store, in the .Client project, calls an API, and the API's endpoints use the server's store:

Browser Page HttpCustomerStore Server API EfCustomerStore Database HTTP
WebAssembly and Auto: the page runs in the browser, and its store calls the server.
HttpCustomerStore.cs (client)
public sealed class HttpCustomerStore(HttpClient api) : ICustomerStore
{
    public async Task<IReadOnlyList<CustomerRow>> ListAsync(CancellationToken cancellationToken = default) =>
        await api.GetFromJsonAsync<List<CustomerRow>>("api/customers", cancellationToken) ?? [];

    public async Task<CustomerRow?> GetAsync(int id, CancellationToken cancellationToken = default)
    {
        using var response = await api.GetAsync($"api/customers/{id}", cancellationToken);
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            return null;
        }
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<CustomerRow>(cancellationToken);
    }
}
Program.cs (server)
var customers = app.MapGroup("/api/customers").RequireAuthorization("Sales");

customers.MapGet("/", (ICustomerStore store, CancellationToken cancellationToken) =>
    store.ListAsync(cancellationToken));

customers.MapGet("/{id:int}", async (int id, ICustomerStore store, CancellationToken cancellationToken) =>
    await store.GetAsync(id, cancellationToken) is { } customer ? Results.Ok(customer) : Results.NotFound());

Both projects need a store

  • Share the interface and the row types. Put ICustomerStore and CustomerRow in the .Client project, which the server project references. Return a type made for the API, not an entity with columns the user shouldn't see.
  • Register a store in both projects. The page prerenders on the server, and an Auto page runs there on the first visit, while the WebAssembly runtime downloads. So the server registers EfCustomerStore and the client registers HttpCustomerStore. With only the client's, prerendering fails. See Microsoft's Prerender components (opens in a new tab).
  • Carry the first load over. The page loads its data once while prerendering and again when it starts in the browser. To skip the second load, persist what the first one read. See Prerendered state persistence (opens in a new tab).
Registering the stores
// Program.cs (server)
builder.Services.AddDbContextFactory<ShopDb>(options => options.UseSqlite(connectionString));
builder.Services.AddScoped<ICustomerStore, EfCustomerStore>();

// Program.cs (client)
builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddScoped<ICustomerStore, HttpCustomerStore>();

A Table or DataGrid sends its sort, filters and page with each load. To send that request over HTTP, see Data from an API.

Checks that move to the server

A user can change code that runs in the browser, and can call your endpoints without your page. So an endpoint repeats every check that the page made:

  • Who can call it. Give the endpoint the policy that the page's [Authorize] names, with RequireAuthorization. See Sign-in across render modes and Microsoft's Blazor authentication and authorization (opens in a new tab).
  • What it accepts. Validate a posted model again in the endpoint. The form's validation in the browser only helps the user.
  • Which rows it returns. If users see only their own records, the store filters by the signed-in user on the server. Don't take the user's id from the request.

Next steps

Connection lost

Rejoining the server…