CORS issue in .NET Core 6 API

Stesvis 1,041 Reputation points
2022-10-04T17:15:28.77+00:00

When I deploy my API to the server and I try to consume APIs from a React app, I always get CORS errors.

I followed this tutorial and nothing works, I get errors such as:

Access to XMLHttpRequest at 'https://backend-dev.livedispatch.ca/api/v3.1/Settings/Clients/3' from origin 'https://dev.livedispatch.ca' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Things I tried:

Method 1

   builder.Services.AddCors(options =>  
   {  
   	options.AddDefaultPolicy(policy => policy  
   		.AllowAnyOrigin()  
   		.AllowAnyHeader()  
   		.AllowAnyMethod()  
   	   );  
   });  
     
   //...  
     
   app.UseCors();  

Method 2

   builder.Services.AddCors(options =>  
   {  
   	options.AddPolicy("CorsPolicy",  
   		policy => policy  
   			.WithOrigins("https://dev.livedispatch.ca"));  
   });  
     
   //...  
     
   app.UseCors("CorsPolicy");  

Method 3

   builder.Services.AddCors(options =>  
   {  
   	options.AddPolicy("CorsPolicy",  
   		policy => policy  
   			.AllowAnyOrigin()  
   			.AllowAnyHeader()  
   			.AllowAnyMethod());  
   });  
     
   //...  
     
   app.UseCors("CorsPolicy");  

Method 4

   builder.Services.AddCors();  
     
   //...  
     
   app.UseCors(options => options  
   	.AllowAnyOrigin()  
   	.AllowAnyMethod()  
   	.AllowAnyHeader());  

I am running out of options, any of these methods still cause CORS errors once deployed.
I am very confused because it SHOULD be straight forward...

Thanks!

Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-10-05T17:32:58.74+00:00

    you are interested in the preflight (option) requests. you must use chrome 83 or greater, and enable all under request filtering.

    in the option request, you are interested in the CORS headers returned. they must meet the rules specified here:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    note: the browser will use these header values to decide whether it is a CORS error or not before making the actual request.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.