React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource

I had a similar problem recently. In my case it started working when I added services.AddCors(); in my ConfigureServices method and this part of code

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

in my Configure method. Remember to add those BEFORE UseMvc() call in both cases.


After two difficult days finally I found out how can I fix my problem. Actually one of your comment was a nice clue for me.

@kirk-larkin said:

The response had HTTP status code 500 is key here. When there's an exception in your ASP.NET Core project, the CORS headers are cleared. You should try and find out why an exception is being thrown.

I traced my code many times, then i found out I forget to register a service which I used in my controller in Startup.cs.

I called these below code in Startup.cs and my problem solved.

services.AddScoped<IMessageService, MessageService>();

With ASP.NET Core 2.1, when the controller throws an exception, which results in an error 500, the CORS headers are not sent. This should be fixed in the next version but until then you could use a middleware to fix this.

see

  • https://github.com/aspnet/CORS/issues/90#issuecomment-348323102
  • https://github.com/aspnet/AspNetCore/issues/2378
  • https://github.com/aspnet/CORS/issues/46

Also note that with credentials you need to explicitly add WithOrigins with host and port since most browsers simply ignore it otherwise (see https://stackoverflow.com/a/19744754/2477619):

  app.UseCors(builder =>
    builder
      .WithOrigins("http://localhost:4200")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
  );