Home > front end >  CORS in .NET 6 AllowAllOrigin not working
CORS in .NET 6 AllowAllOrigin not working

Time:01-05

I am trying to allow requests from other domains to my app in Startup.cs (in .NET Core 6).

In ConfigureServices(IServiceCollection services):

services.AddCors(options => options.AddDefaultPolicy(policy =>
                  {
                      policy
                      //.AllowAnyOrigin() // <- I also tried this
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .SetIsOriginAllowed(origin => true); // <- instead of this
                  }));

I also tried AddPolicy instead of AddDefaultPolicy.

In Configure(IApplicationBuilder app, IWebHostEnvironment env):

app.UseCors(_corsAllPolicy);

I am still getting

Access to script at 'https://localhost:44306/dist/js/build.js' from origin 'http://customdomain.com' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local.

Is there something I'm missing?

CodePudding user response:

Problem solved, I should have paid more attention to the error comment:

The request client is not a secure context

Basically the domain was not secure and was calling script that was under secure domain. I am calling now from a secure domain and it is working.

Thanks for reassuring me that my code was correct :)

CodePudding user response:

Make Sure you've called app.UseCors before app.UseStaticFiles

And if you try with the default policy:

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        policy =>
        {
            policy.WithOrigins("");
        });
});

just call:

app.UseCors();

don't add any parameters in the method, And you could check the related document for more details

if you still got the error,please provide the minimal codes that could reprodce your error

  • Related