Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Web Api sending Access-Control-Allow-Origin: null CORS header and chrome is erroring, how to fix?

Yesterday I managed to have my API working on my local computer, however today (same code) on another computer, it's not working, I am getting this error on the console:

Failed to load http://localhost:52056/api/task: The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.

Here is the http request and response on Chrome:

enter image description here

(I don't see errors in IE/Firefox)

Here is my startup class (using .net core 2)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TodoApi;

namespace TestCors
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<ITaskWarehouse, TaskWarehouse>();

            services.AddCors();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            app.UseMvc();
        }
    }
}

What is wrong here? The code is the same from yesterday, however I was running on Windows 10 and this machine has Windows 7. Any thoughts? Thanks

like image 547
TiagoM Avatar asked Mar 15 '18 13:03

TiagoM


1 Answers

Try removing

.AllowCredentials()

CORS doesn't allow you to have .AllowCredentials() AND .AllowAnyOrigin() for the same policy. I don't why it worked on a different machine.

This is from ASP.NET page

The CORS spec also states that setting origins to "*" is invalid if SupportsCredentials is true.

like image 194
Simply Ged Avatar answered Sep 26 '22 01:09

Simply Ged