0

Trying to access a local API made in web API 2.0 (asp.net) from an angular project.

The request results in

Access to XMLHttpRequest at 'http://localhost:50581/MD/GetUserMD' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

But I don't understand as I added EnableCors to the webAPIConfig

enter image description here

and specified these in all the controllers. enter image description here

Is there something I could try to resolve this issue? Thank you in advance.

Jorido
  • 25
  • 6

1 Answers1

1

CORS allows you to specify who is able to call your API. So more is needed than just enabling CORS; you need to set the policies. There are a couple ways to do that:

  1. With the [EnableCors] attribute, which can be set at either the Controller or Action level:
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
  1. For your entire application:
public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("[EnableCors(origins: "http://localhost:4200", "*", "*");
    config.EnableCors(cors);
}

You can set the origin to "*" to allow any website to make requests to your API, but be careful with that.

More information here: Enable cross-origin requests in ASP.NET Web API 2

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
  • Thank you for your comment, Gabriel! I found out that Chrome blocks localhost API calls for security reasons and so I have been developing with web security disabled. Do you know a way to resolve this? – Jorido Jan 12 '22 at 23:19
  • According to [this answer](https://stackoverflow.com/questions/66534759/chrome-cors-error-on-request-to-localhost-dev-server-from-remote-site), Chrome will block it unless 1. The main site is HTTPS and 2. The API has appropriate CORS headers. So with my answer you can satisfy #2. To satisfy #1, you need to enable HTTPS on your `localhost:50581` site. If that is a development site in Visual Studio, follow [this answer](https://stackoverflow.com/a/41341491/1202807). – Gabriel Luci Jan 13 '22 at 00:56
  • I'll make sure to try, thank you for your answer! – Jorido Jan 14 '22 at 02:31