I had the same problem with OPTIONS requests being denied but it turned out to be related to how I was re-using the AllowedHosts string in the .WithOrigin() call...
I ended up in a situation where if I entered the scheme or port into the appsettings.json's AllowedHosts then .Net would block the request with something like this:
[DBG] The request has an origin header: 'http://localhost:3000'.
[INF] CORS policy execution failed.
[INF] Request origin http://localhost:3000 does not have permission to access the resource.
... but if I didn't include the scheme or port then I couldn't re-use the same data in the .WithOrigins() call (and I didn't want to hard-code the hosts).
The solution for me in the end was sadly to create another property in appsettings.json that I could split and feed into .WithOrigins() like so:
appsettings.json
"AllowedHosts": "localhost;anotherdomainname.co.uk",
"AllowedCorsHosts": "http://localhost:3000;https://anotherdomainname.co.uk,"
Program.cs
builder.Services.AddCors(options =>
{
string[] origins = builder.Configuration["AllowedCorsHosts"].Split(';');
options.AddDefaultPolicy(
corsBuilder =>
{
corsBuilder.WithOrigins(origins);
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowCredentials();
});
});
This appears to satisfy both the internal .Net CORS code and allows me to specify hosts without hard-coding them.
[DBG] Allowed hosts: localhost; anotherdomainname.co.uk
....
[DBG] The request has an origin header: 'http://localhost:3000'.
[INF] CORS policy execution successful.
[DBG] The request is a preflight request.
N.B. Don't just remove the AllowedHosts entry from appsettings.json entirely or .Net will default to allowing any host!
[DBG] Wildcard detected, all requests with hosts will be allowed.
I hope this helps someone