简体   繁体   中英

CORS issue while calling WEB API using angular js

I am working on my first demo application which is used to display person details on UI using web api and angular JS. My code is working fine if I am launching Chrome using "chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security", however it's not working for normal Chrome/IE. I did some debugging and found that seems CORS issue. I tried to enable CORS at api end as well but not working for me. Can someone please help me to make it working. Thanks in advance. Below is my code snippet:

WebAPI:

  public class HomeController : ApiController { public HttpResponseMessage GetPersonDetails() { var person = new List<person> { new Person {Id=1, Address="Pune", Name="Test1"}, new Person {Id=2, Address="Pune", Name="Test2"}, new Person {Id=3, Address="Pune", Name="Test3"}, new Person {Id=4, Address="Pune", Name="Test4"} }; return Request.CreateResponse(HttpStatusCode.OK, person); } } 

angular code:

 var appModule = angular.module("MyApp", []); appModule.controller('getUserDetailsController', function ($scope, $http) { $http({ method: 'GET', url: 'http://localhost:61896/api/Home/GetPersonDetails', headers: { 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Origin': '*' }, contentType:'text/plain; charset=UTF-8' }).then(function (response) { $scope.objUserDetails = response.data; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 

I tried to enable CORS at api end, also tried to send header from js, but nothing worked for me.

As per your reply, there are few corrections that you need to make in your attribute.

  • Remove semicolon from orgins
  • Add * in headers and methods

    [EnableCors(origins: " http://localhost:61896 ", headers: " ", methods: " ")]

Just use above EnableCors attribute as it is and your issue should be resolved.

Note: Somehow * is always removed when i post the answer. Don't forget to add * if its not there in your headers and methods.

Second thing is to look for having config.EnableCors() in your Register method of WebApiConfig.cs file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM