Reputation: 7
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.
I have install CORS nuget package in the API.
I tried to add EnableCorsAttribute and config.EnableCors in WebAPIConfig.cs file but it is also showing error.
Below is the Chrome screenshot:
**EnableCorsAttribute Error **
Upvotes: 0
Views: 1427
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
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