2

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?

1
  • How do you enable cors in web api? Commented Jun 30, 2017 at 6:28

2 Answers 2

2

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://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.