I have an ASP.NET Core 8.0 Web API, hosted in Azure. It works fine when everything is deployed to Azure. But we are trying to run a Reactjs front end locally and access that Web API in Azure for testing and debugging. I have followed all the docs about setting up CORS on the web service, but keep getting:
Access to fetch at 'https:///api/stats' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
builder.Services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
policy => {
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
builder.Services
.AddControllers()
.AddJsonOptions(x =>
{
x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
x.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
Then, later on, after doing var app = builder.Build()
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers()
.RequireCors(MyAllowSpecificOrigins);
});
app.UseSpa(spa =>
{
if (builder.Environment.IsDevelopment())
{
spa.Options.SourcePath = "client-app";
spa.UseReactDevelopmentServer("start");
}
});
I've even tried adding [EnableCors(MyAllowSpecificOrigins)] to the controller itself.
This is for an open source project for a non-profit. Hoping someone knows the solution. Any ideas?
Here is the Program.cs in its entirety:
https://github.com/TrashMob-eco/TrashMob/blob/main/TrashMob/Program.cs
I have tried changing order of statement, tried old approaches and new from searches, tried opening up all origins. Nothing seems to work.


CORS settingswhere you should have 'localhost:3000` as an allowed origin. Apart from this your code seems correct.