0

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?

1 Answer 1

1

In ConfigureServices put:

services.AddCors();

and in Configure put:

app.UseCors(builder => builder.AllowAnyOrigin()
                              .AllowAnyHeader()
                              .AllowAnyMethod());
Sign up to request clarification or add additional context in comments.

1 Comment

I'm using core 6 so I don't have thos functions. I only have the program.cs file. I added services.AddCors(); and that worked. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.