I have a web api in .net core 6
What I want is to enable cors from all origins.
when I add policy just for localhost it works fine, but when I change my policy to allow any origin, I get the error –
Access to XMLHttpRequest at ‘…’ from origin ‘http://localhost’ 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.
My code:
...
/* NOT working */
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "any",
policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
/* Works fine*/
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "local",
policy =>
{
policy
.WithOrigins("http://localhost")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
...
app.UseCors("any");
/* OR */
app.UseCors("local");
Any idea why?
>Solution :
In ConfigureServices put:
services.AddCors();
and in Configure put:
app.UseCors(builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());