pradeep
pradeep

Reputation: 7

Enable CORS in Asp.Net Application

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

Upvotes: 0

Views: 1427

Answers (2)

WhatsThePoint
WhatsThePoint

Reputation: 3635

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()

Upvotes: 1

Ishwor Khatiwada
Ishwor Khatiwada

Reputation: 174

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);

Upvotes: 0

Related Questions