3

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

Atabai Fekri
  • 301
  • 2
  • 4
  • 20

3 Answers3

3

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

Atabai Fekri
  • 301
  • 2
  • 4
  • 20
2

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

app.UseCors(builder => builder.WithOrigins("*")
                               .AllowAnyMethod()
                               .AllowAnyHeader());
Bhavin Varsur
  • 317
  • 1
  • 15
2

Add this above your Api Class

[EnableCors(origins: "https://rushpeik.ir", headers: "*", methods: "*")] 
public class YourController : ApiController
{
        // Whatever
}
Mertez
  • 1,061
  • 3
  • 14
  • 38