How do you call an existing ASP.NET Core minimal API or controller endpoint from a Blazor WebAssembly component using HttpClient?
Short answer
Blazor WebAssembly components inject a configured HttpClient (registered in Program.cs with a BaseAddress pointing to the hosting API), then call standard HttpClient methods (GetFromJsonAsync, PostAsJsonAsync) just like any other .NET client application would, since WebAssembly…
Advertisement
AModel answer
Blazor WebAssembly components inject a configured HttpClient (registered in Program.cs with a BaseAddress pointing to the hosting API), then call standard HttpClient methods (GetFromJsonAsync, PostAsJsonAsync) just like any other .NET client application would, since WebAssembly components run entirely in the browser and communicate with the backend purely over HTTP, unlike Blazor Server which can directly inject and call backend services in-process.
// Program.cs (Blazor WebAssembly client project)
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// Component
@inject HttpClient Http
@code {
private Product[]? products;
protected override async Task OnInitializedAsync() {
products = await Http.GetFromJsonAsync<Product[]>("api/products");
}
}Real-world example
A Blazor WebAssembly storefront fetches its product catalog by calling the same /api/products minimal API endpoint that a separate mobile app also consumes, since WebAssembly components communicate purely over HTTP just like any other API client.
Likely follow-ups
- Why can't Blazor WebAssembly directly inject and call backend services in-process the way Blazor Server can?
- How do you handle CORS if the WebAssembly app is hosted separately from its API?
Related topics