I am building a .Net 5 Web API and I am having issues with CORS only when I am running locally (aka localhost). When I have deployed my app to Azure I can access my API just fine from my Blazor app.
Class Startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
Class: Startup.cs
Method: ConfigureServices
services.AddCors(options =>
{
//didn't work
//options.AddDefaultPolicy(builder =>
//{
// builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
//});
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://localhost:44373/", "https://myawesomesite")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Class: Startup.cs
Method: Configure
app.UseCors(MyAllowSpecificOrigins);
Just remove trailing "/" from your local host url and for the test you can try to remove .AllowCredentials().
And use this syntax:
services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://localhost:44373",
"https://myawesomesite")
.AllowAnyMethod()
.AllowAnyHeader();
}));
and your UseCors method should be between UseRouting and UseAuthourization
app.UseRouting()
....
.....
app.UseCors(MyAllowSpecificOrigins);
....
....
app.UseAuthorization(); // if you need the one