I’ve set up CORS in the request pipeline in an ASP.NET Core Web Api/ReactJS SPA. Reading the logs I see that the CORS policy is set up correctly but none of the requests are actually failing. For example, where’s the log output for one post request where I’m using an origin that’s not specified in AllowedOrigins:
2024-09-23 21:23:42.7074||INFO|Microsoft.AspNetCore.Cors.Infrastructure.CorsService|CORS policy execution failed.
2024-09-23 21:23:42.7074||INFO|Microsoft.AspNetCore.Cors.Infrastructure.CorsService|Request origin https://localhost:44498 does not have permission to access the resource.
2024-09-23 21:23:42.7074||INFO|Microsoft.AspNetCore.Routing.EndpointMiddleware|Executing endpoint 'TweetController.PostTweet (releaseplanb)'
But here’s the crazy part, the request is still succeeding with a 200 status. It doesn’t get caught at the server level and I’m not noticing any Access-Control-Allow-Origin response headers. I’m using Fetch to make the requests in the React front end.
UPDATE: It appears that that the “Access-Control-Allow-Origin” header is actually being generated on a successful policy. I added this custom header in Chrome Dev Tools and saw it populated on success but empty on cors policy failure. So that part seems to be working correctly.
What I was expecting to happen is to see some browser message that the request failed due to Cors or that ASP.NET Core would disallow the request.
using Microsoft.Extensions.FileProviders;
using NLog;
using NLog.Web;
var builder = WebApplication.CreateBuilder(args);//WebApplicationBuilder
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Debug("init main");
builder.Logging.AddNLogWeb("nlog.config");
builder.Host.UseNLog();
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(o=>o.WithOrigins("https://localhost:44497")
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("Access-Control-Allow-Origin"));
});
builder.Services.AddControllers();
var app = builder.Build();
if (!app.Environment.IsDevelopment()) {
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseExceptionHandler("/Home/Error");
} else {
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(app.Environment.ContentRootPath,"ClientApp")),
RequestPath = "/StaticFiles"
});
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
//app.MapFallbackToFile("index.html");
app.Run();
1