Configure CORS on Back-End Web API
Symptoms
When your front-end Blazor Client is not hosted by your back-end Web API you’ll likely hit a common problem: missing CORS headers.
By default .NET Core Web API will not include any CORS headers. So, in the absence of headers, modern web browsers will enforce a default same origin policy. That is your Blazor client, on a different origin than your API, will not be allowed to make API requests.
Diagnosis
To be sure that you do have a CORS problem, open the Developer tools in your browser. Then, select the Network tab and reload your page. Under Status you will see “CORS error” and you can mouse over the message get details.
Fix
As with most security concerns the buck stops with the back-end. (The front-end has no control over cross-origin permissions.) Fortunately adding CORS headers is simple with ASP .NET Core.
So this works across different environments
we will make it configurable.
Add an app setting for WebClientOrigin
.
appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WebClientOrigin": "https://localhost:44353"
}
The production setting can be set in appsettings.json
or via the server environment.
In Startup.cs
add calls to AddCors
and UseCors
in ConfigureServices()
and Configure()
respectively.
public void ConfigureServices(IServiceCollection services)
{
// ...
// Configure CORS for Blazor Web Client
const string ClientOriginKey = "WebClientOrigin";
var clientOrigin = Configuration.GetValue<string>(ClientOriginKey);
if (clientOrigin is not null)
{
services.AddCors(cors =>
{
cors.AddDefaultPolicy(policy => policy.WithOrigins(clientOrigin)
.AllowAnyHeader()
.AllowAnyMethod());
});
}
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseRouting();
// Use Default CORS policy for Blazor Client
app.UseCors();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
The above approach can easily be extended to support multiple client origins.
ASP .NET CORS configuration is far more versatile than what’s shown here. If you need something more tailored, it can be customized along any dimension.