The Problem
How hard can it be to configure CORS in a .NET Core 3.1 WebAPI? The answer…quite hard.
The Microsoft documentation shows how to configure CORS and it should be straightforward. However, my experience and the exeperience of many others on StackOverflow have shown me that all is far from simple….Although the solution, when finally found was remarkably simple.
Code
CORS can be configured on the ConfigureServices method in Startup.cs with more or less:
services.AddCors(options => { options.AddPolicy(name: "myCORSPolicy", builder => { builder.WithOrigins(this.ApiConfiguration.CorsOrigins.ToArray()); builder.AllowAnyMethod(); builder.AllowAnyHeader(); builder.AllowCredentials(); }); });
and in the Configure method
app.UseCors("myCORSPolicy");
First Problem
So..I’m on an internal development network and I want to allow all origins (i.e. “*”) and AllowCredentials (as I want to use Active Directory).
Wrong!
The combination of .WithOrigins(“*”) and AllowCredentials is expressly forbidden and will generate a run-time exception.
Second Problem – Trailing Slashes
The .WithOrigins takes a “list” of origins i.e. URLs which can access your API. These must not have trailing slashes, e.g.
http://mydomain.comĀ - works http://mydomain.com/ - CORS will not allow access from this origin
Microsoft do mention this in their documentation. however, it is far from clear and easily overlooked.