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..