How do you configure CORS correctly when a Blazor WebAssembly app is hosted on a different origin than its backend API?
Short answer
Since Blazor WebAssembly runs entirely in the browser, cross-origin calls from the WASM app to a separately-hosted API are subject to the exact same browser CORS restrictions as any other JavaScript-based SPA -- the API must explicitly configure a CORS policy (via…
Advertisement
AModel answer
Since Blazor WebAssembly runs entirely in the browser, cross-origin calls from the WASM app to a separately-hosted API are subject to the exact same browser CORS restrictions as any other JavaScript-based SPA -- the API must explicitly configure a CORS policy (via AddCors/UseCors) allowing the WebAssembly app's origin, exactly as you would for a React or Angular frontend.
// API's Program.cs
builder.Services.AddCors(options => {
options.AddPolicy("BlazorClient", policy =>
policy.WithOrigins("https://blazor-app.mycompany.com").AllowAnyMethod().AllowAnyHeader());
});
app.UseCors("BlazorClient");Real-world example
A Blazor WebAssembly app deployed to a static hosting CDN calls a separately-deployed ASP.NET Core API on a different domain, requiring the API to explicitly whitelist the WebAssembly app's origin via standard CORS configuration, identical to any JavaScript SPA integration.
Likely follow-ups
- Does Blazor Server have the same CORS considerations as WebAssembly?
- How does hosting both the API and WASM app from the same ASP.NET Core project avoid this CORS configuration entirely?
Related topics