skip to Main Content

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

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. 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()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search