I can't seem to enable CORS in my ASP.NET Core 7 MVC web app.
Given it didn't work, I've tried to make the simplest possible example that should have it working, based on the documentation here and several questions on this site.
It still doesn't appear to work. I'm now slight doubting my testing methodology: I'm calling it with postman and hoping to see a "Access-Control-Allow-Origin", "*"
header.
My program.cs
looks like this: note that I have removed everything not directly needed to just make it run and have CORS enabled:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
app.MapControllers();
app.Run();
For testing I have used postman:
I was receiving the following headers:
As pointed out by the correct answer below, what I wasn't doing was sending origin. Fixing that fixed the problem. I've run the code on a different machine, on the same network, because I read somewhere that if you test from localhost to localhost the header doesn't always get added
You aren't sending an Origin
header (I had to squint; please express your request configuration as text not a picture), so the request does not appear to be one that needs permission from CORS. Many CORS handling libraries won't add CORS permission for non-CORS requests.