1

I have an IONIC/AngularJS application from which I have to call my ASP.NET MVC controller method i.e Login. It works with fine with $http.get() but when I use $http.post() or $http({method: 'POST'}) it returns an error. The error is (for Chrome):

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have enabled CORS for Server by following the answer to this question:

CORS in ASP .NET MVC5

I also included nuget package to enable CORS, but this didn't solve my problem. I also tried adding the following in Angular's POST request:

$http({
     method: 'POST',
     url: url,
     headers: {'Access-Control-Allow-Origin': '*'},
     data: _data}).then();

but it didn't work either. Please let me know if I am missing something.

Thankx

Community
  • 1
  • 1
geekowls
  • 627
  • 7
  • 17

2 Answers2

3

Add this to your web.config file

<system.webServer>
  <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>
</system.webServer>
Marlon Vidal
  • 669
  • 4
  • 14
  • I ran into another issue after I successfully hit my post method. The error i received was: "XMLHttpRequest cannot load http://url Response for preflight has invalid HTTP status code 404". So i included the following with my post requests: $httpProvider.defaults.headers.post = {}; Now it hits my post method, but my method is returning an error with null data. Any idea what's going on? – geekowls Jun 25 '16 at 07:01
2

Add this to your WebApiConfig

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
  • 1
    Do you need to register that somewhere? I imagine that just creating the variable doesn't do anything after it goes out of scope. – krillgar Jun 23 '16 at 13:44