Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL has been blocked by CORS policy

Tags:

c#

asp.net-mvc

I'm getting below error on calling API from ASP.Net MVC in angular version 1

enter image description here 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

like image 439
Atabai Fekri Avatar asked Dec 01 '25 06:12

Atabai Fekri


2 Answers

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

like image 198
Atabai Fekri Avatar answered Dec 03 '25 19:12

Atabai Fekri


Here you need to add this in your Configure() method in your startup.cs

app.UseCors(builder => builder.WithOrigins("*")
                               .AllowAnyMethod()
                               .AllowAnyHeader());
like image 45
Bhavin Varsur Avatar answered Dec 03 '25 19:12

Bhavin Varsur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!