Wednesday, July 8, 2015

Getting Angular's $http.post method working with Web API

By default, when you deploy a .Net Web API project, you are not allowed to make cross site requests to it from, say, an angular application.  The browser will prevent the call from happening because your api needs to send the proper response header to allow the call to be made.

In order to enable it, you need to make a modification to your web.config file.  Enter the following somewhere between your system.webServer tags:
<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>
Also, in your ApiController, add an empty Options method (some browsers issue this command to check the validity of a cross origin request):
    public class DataController : ApiController
    {
        public void Options() { }
    }


No comments:

Post a Comment