0

I am getting "Access to XMLHttpRequest at 'http://localhost:60261/api/student/?Name=qwwertyqwe&Age=21' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Although the API is called and it is working as expected, but there is Error thrown at Chrome console. Things I have done.

  1. I have install CORS nuget package in the API.

  2. I tried to add EnableCorsAttribute and config.EnableCors in WebAPIConfig.cs file but it is also showing error.

Below is the Chrome screenshot: enter image description here

**EnableCorsAttribute Error ** enter image description here

**config.EnableCors Error ** enter image description here

pradeep
  • 11
  • 1
  • 10
  • is this a reactjs aspnet core project? – Josh Feb 06 '23 at 10:12
  • the API is in basic ASP.NET and I am calling the API in an Angular Application. – pradeep Feb 06 '23 at 10:19
  • i dont know if its the same with angular but with react you have to create a Proxy between api and front end ill add example – Josh Feb 06 '23 at 10:23
  • https://stackoverflow.com/questions/71830055/proxy-conf-js-not-working-in-asp-net-core-app-with-angular – Josh Feb 06 '23 at 10:24
  • In my opinion, to fix this issue, you will need to add the "Access-Control-Allow-Origin" header to the API response, indicating that requests from the specified origin are allowed – Ishwor Khatiwada Feb 06 '23 at 10:32
  • @IshworKhatiwada Please elaborate, because I am also not able to add var corsAttr = new EnableCorsAttribute("*","*","*") ; config.EnableCors(corsAttr); in WebApiConfig.cs file. – pradeep Feb 06 '23 at 10:36
  • 1
    During development, you don't need to configure CORS yet, https://angular.io/guide/build#proxying-to-a-backend-server When you deploy to production, you can use a real reverse proxy (IIS+ARR or nginx). – Lex Li Feb 06 '23 at 17:43

2 Answers2

1

Add this to your program.cs or wherever your application is built

var app = builder.Build();
...
app.UseCors(policy => policy.AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials()
                            .WithOrigins("https://localhost:4200"));

Do note that the UseCors() needs to be called before UseAuthentication() and UseAuthorization()

WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53
0

add the [EnableCors("", "", "*")] attribute to the API controller or method that you want to allow requests from other domains. Or, In the WebAPIConfig.cs file, you can enable CORS globally.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);