1

I'm beginner in Angular 2. I'm creating Angular project using Angular CLI. I'm separately creating asp.net MVC Web api project.

  • Using angular CLI to ng serve command start this service: localhost:4200
  • MVC web api start this service: localhost:65320

When i use Angular http get request to download data from localhost:65320/api/myservice, Cross origin problem occurred. Because angular project using different url. But i'm adding header to Access-Control-Allow-Origin=* problem solved.

But when i use http post request always return 405 method not allowed problem occurred

Question:

  • How to allow cross origin post request in web api controller?
  • Or how to configure Angular CLI created project work together with MVC project?

Correct Answer:

Web api cross origin problem solved following this article: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors suggest by @chandermani

4
  • 1
    Have you looked at this msdn article asp.net/web-api/overview/security/… Commented Jan 5, 2017 at 7:58
  • @Chandermani no. i will see. tnx Commented Jan 5, 2017 at 8:01
  • @Chandermani Thank you. Your link solve my Cross Origin request POST problem . Commented Jan 5, 2017 at 8:15
  • 1
    Great! post your fixes as an answer, so it can be marked Commented Jan 5, 2017 at 8:46

1 Answer 1

0

You can enable CORS in Web API in two different ways:

  1. Using Microsoft.AspNet.WebApi.Cors: follow tutorial https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api as Chandermani pointed out.
  2. Add the following to your system.webServer element in your 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" /> </customHeaders> </httpProtocol>

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

2 Comments

I'm trying your option 2. But POST request always return 405 method Not allowed. Now i'm solving problem using Microsoft.AspNet.WebApi.Cors library
In some scenarios of the CORS Specification the client sends a Preflighted Request to the server using the OPTIONS method, which you probably did not implement, hence the 405 method not allowed. This is automatically implemented by Microsoft.AspNet.WebApi.Cors, but was not available in older versions of MVC.

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.