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() { }
    }


3 comments:

  1. Articles on Oman Report provide comprehensive coverage of technological advancements, economic developments, energy initiatives, tourism insights, and cultural updates, offering readers actionable knowledge and context on Oman’s modern progress.

    ReplyDelete
  2. Insightful articles on Spain Journal offer readers perspectives on technology, innovation strategies, and market trends, helping audiences interpret developments and understand Spain’s contribution to global digital transformation.

    ReplyDelete
  3. By delivering accurate reporting and well-crafted commentary, News Loss ensures readers gain valuable knowledge on trends, key stories, and important updates that shape the contemporary world.

    ReplyDelete