2
votes

I have rest application with Angular2 and ASP MVC rest server and I have a problem with communication. When I send get, I get this error:

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

When I added Access-Control-Allow-Origin to request, I get this error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.

Here is my code:

let headers = new Headers({ 'Access-Control-Allow-Origin': '*' })
    this.http.get("http://localhost/App/Users", { withCredentials: true, headers: headers })
      .subscribe(response => {
        console.log("A");
      }, error => {
        console.log(error);
      });

In web.config is enabled Windows authentication. Where is problem?

2
How do you enable cors in web api?hasan

2 Answers

2
votes

The problem seems here is of CORS. Your angular and WebAPI are using different ports as you're using localhost. (Seems like they are two different projects). To solve this you can install the nuget package using "Install-Package Microsoft.AspNet.WebApi.Cors" and then in your WebApiConfig file you can simply say "config.EnableCors()". Now the API which you're exposing to the angular part, has to be told that the CORS is supposed to be used there. So you can put the attribute over your controller mentioning the origin, headers and methods. It should work fine after that. For more reference, you can check this link, https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

0
votes

On server side when you enabled cors add:

corsAttr.SupportsCredentials = true;

Like this on MVC .net on Application_Start

var corsAttr = new EnableCorsAttribute("http://localhost:4200,http://domain1,http://domain2", "*", "*");
// Enable withCredentials
corsAttr.SupportsCredentials = true;
config.EnableCors(corsAttr);