2

I've a problem for sending data to the server via POST/DELETE. I always get a CORS error when I'm trying to send data to the WebAPI. The client-side was implemented with AngularJS and the server-side with ASP.NET WebAPI by C#.

Here's the Code of server-side WebAPI:

//Model:
public class TestRepository : ITestRepository
    {
        private List<Person> persons = new List<Person>();

        public TestRepository()
        {
            Add(new Fond { id = "DE001", fname = "John", age = 32 });
            Add(new Fond { id = "DE002", fname = "Jeffrey", age = 23 });
        }

        public IEnumerable<Person> GetAll()
        {
            return persons;
        }

        public Person Add(Person item)
        {
            if (item == null) {
                throw new ArgumentNullException();
            }

            persons.Add(item);
            return item;
        }

        public bool Delete(string id)
        {
            fonds.RemoveAll(p => p.id == id);

            return true;
        }
}

//Controller
    public class TestController : ApiController
        {
            static readonly ITestRepository rep = new TestRepository();

            // GET api/fond
            public IEnumerable<Person> GetAllPersons()
            {
                return rep.GetAll();
            }

            // POST api/fond
            [HttpPost]
            public Person PostPerson(Person item)
            {
                return rep.Add(item);
            }

            // DELETE api/fond/5
            public bool DeletePerson(string id)
            {
                if (rep.Delete(id))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

I've installed the Nuget Package Microsoft.AspNet.WebApi.Cors. In the WebApiConfig file I've added following lines:

 ...
 var cors = new EnableCorsAttribute("http://localhost:63831", "*", "*");
 config.EnableCors(cors);

And the client-side Code:

//Get the list works!
$scope.list = ResService.person.query();

//Delete doesn't work
$scope.deletePerson = function (removePers) {
    $scope.res = ResService.person.remove(function () {
        $log.info('[Resource]', $scope.res);
        $scope.res.$delete(removeItem);
    });
};

//Post doesn't work
$scope.addPerson = function (newPers) {
  var persObj = {
      id: newPers.id,
      fname: newPers.fname,
      age: newPers.age
  };

  $http.post(baseUrl + '/api/person', persObj).success(function (persData) {
      $scope.list.push(persData);
  }).error(function (message) {
      $log.error(message);
  });

Only GetAll function works. When I'm using POST or DELETE then comes an error message Cross-Origin-Request blocked..

yuro
  • 2,189
  • 6
  • 40
  • 76
  • If you monitor the actual calls made, do you see an extra request made when doing a POST or DELETE? Like the pre-flight OPTIONS request? – Sam Storie May 28 '15 at 13:24
  • @SamStorie Yes I get a OPTIONS request. – yuro May 28 '15 at 14:18
  • Are you sure localhost:8080 is used by your angular app? – Wayne Ellery May 28 '15 at 14:43
  • @WayneEllery No, the right path is: localhost:63831. That was only an example with localhost:8080, but with the right path it is also the same error. I've searched for a solution and found `https://msdn.microsoft.com/en-us/magazine/dn532203.aspx` this site with the title `Preflight CORS Requests`. Do I have to define the OPTIONS-HTTP-Request in my WebAPI? – yuro May 28 '15 at 14:46
  • No, you shouldn't. What browser are you using? Is it possible to try something other than localhost and see if it works? – Wayne Ellery May 28 '15 at 14:47
  • @WayneEllery Currently Firefox 38.0.1.. No at the moment I only can use localhost because I'm at work. – yuro May 28 '15 at 14:49
  • The error message tells: (Reason: CORS-Header 'Access-Control-Allow-Origin' does not match '*' – yuro May 28 '15 at 14:53
  • Are you sure you are using `new EnableCorsAttribute("http://localhost:8080", "*", "*")` and not `new EnableCorsAttribute("*", "*", "*")` – Wayne Ellery May 28 '15 at 14:59
  • I'm using `var cors = new EnableCorsAttribute("http://localhost:63831", "*", "*");` I've also tried `new EnableCorsAttribute("*", "*", "*");` but it is the same problem. – yuro May 28 '15 at 15:03
  • When I set `new EnableCorsAttribute("*", "*", "*");` then the GET method also doesn't work. – yuro May 28 '15 at 15:11
  • What is the value of the Access-Control-Allow-Origin header in the request(should be able to see this in your browsers dev tools)? – peinearydevelopment Jun 15 '15 at 19:57
  • @peinearydevelopment I've solved this problem. Only this configuration worked in my project respectively in the WebApiConfig File: `var cors = new EnableCorsAttribute( origins: "http://localhost:...", headers: "*", methods: "*"); config.EnableCors(cors);` But I have problems in this topic: [Click here](http://stackoverflow.com/questions/30780808/reset-the-changed-values-doesnt-work-in-other-ctrl-angularjs) If you could help me that would be great :) – yuro Jun 16 '15 at 07:13

0 Answers0