Marc Rasmussen
Marc Rasmussen

Reputation: 20565

NET Core Cors throws error

So I have the following:

public void ConfigureServices(IServiceCollection services)
{
    var corsBuilder = new CorsPolicyBuilder();
    corsBuilder.AllowAnyHeader();
    corsBuilder.AllowAnyMethod();
    corsBuilder.AllowAnyOrigin();
    corsBuilder.AllowCredentials();

    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins", corsBuilder.Build());
    });

    services.AddDbContextPool<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    services.Configure<Infrastructure.FileOptions>(Configuration.GetSection("Files"));
    services.AddTransient<Infrastructure.ServiceCollection>();
}

As you can see I am allowing everyone to access my routes.

However, when I try to access a route I get the following error:

Failed to load https://localhost:44381/test: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

What have I done wrong?

Upvotes: 1

Views: 138

Answers (2)

Souvik Ghosh
Souvik Ghosh

Reputation: 4616

I faced the similar issue. I tried it like this-

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("CORSPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
    }));
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CORSPolicy");
}

Also, if you host this on Azure, you need to do the CORS setting in Azure as well.

Upvotes: 1

OrcusZ
OrcusZ

Reputation: 3660

You should add in the configure method this line

app.UseCors("AllowAllOrigins");

This activate the AllowAllOrigins that you configure in the services.

Upvotes: 2

Related Questions