I'm getting below error on calling API from ASP.Net MVC in angular version 1
Error:
Access to XMLHttpRequest at 'URL 1' from origin 'URL 2' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I use below code in WebApiConfig:
var corsAttr = new EnableCorsAttribute("*","*","*");
config.EnableCors(corsAttr);
After that I tried to use below code :
var corsAttr = new EnableCorsAttribute("*","Content-Type", "GET,POST,PUT,DELETE,OPTIONS");
config.EnableCors(corsAttr);
and:
var corsAttr = new EnableCorsAttribute("https://rushpeik.ir","Content-Type", "GET,POST,PUT,DELETE,OPTIONS");
config.EnableCors(corsAttr);
But the problem remains
I found the solution:
At the first have to use below code in WebApiConfig
var corsAttr = new EnableCorsAttribute("*","*","*");
config.EnableCors(corsAttr);
After that add below code to web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
We have to allow all custom headers in "Access-Control-Allow-Headers" like below line:
<add name="Access-Control-Allow-Headers" value="Content-Type,Token,Username" />
It worked for me :)
Here you need to add this in your Configure() method in your startup.cs
app.UseCors(builder => builder.WithOrigins("*")
.AllowAnyMethod()
.AllowAnyHeader());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With