Search code examples
asp.net-web-apicorsangular2-servicesaccesscontrolexception

No 'Access-Control-Allow-Origin' error when accessing web-api from angular2


From one side I have an ASP.net web application that contains a web api module. On the same machine I have an angular 2 client application which is consuming the web api controllers crud methods. The angular 2 uses a basic http service with the uri of the localhost with the port number on which the web api runs on. I run the web api application and when the angular 2 tries to consume a Get request, I get this error message (22770 is the port of the web-api, 4200 is the port of the angular 2 application):

Failed to load http://localhost:22770/api/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Although this is quite a common question, mine is a little bit different: CORS is defined as: Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to let a user agent gain permission to access selected resources from a server on a different origin (domain) than the site currently in use

BUT - I'm working with the same domain - on my local machine (localhost).

What is the problem and how can I solve it ?


Solution

  • You need to enable CORS (cross origin request) in your web api. Follow instruction given in below page

    https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api