Search code examples
angularpostcorshttp-headersasp.net-core-2.0

Web API core 2.0 cors issue (header is present) not allowed access


I'm trying to perform post request from angular http://localhost:4200 to webApi core 2.0 and I'm getting this in my console

Failed to load _http://localhost:62066/api/values: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I tried adding cors like this but I get same error; what is the right way to do it?

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(builder => builder.WithOrigins("http://localhost:4200"));
            app.UseCors(builder=> builder.WithHeaders("http://localhost:4200"));
            app.UseMvc();
        }

Solution

  • in startup.cs add new cors with allowany on everything because when allowing only header request still doesn't work

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

    and use it here

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseCors("AllowAll"); //<===
                app.UseMvc();
            }