我通过POST / DELETE向服务器发送数据存在问题。 当我尝试将数据发送到WebAPI时,我总是收到CORS错误。 客户端使用AngularJS实现,服务器端使用ASP.NET WebAPI通过C#实现。
这是服务器端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;
}
}
我已经安装了Nuget Package Microsoft.AspNet.WebApi.Cors
。
在WebApiConfig文件中,我添加了以下行:
...
var cors = new EnableCorsAttribute("http://localhost:63831", "*", "*");
config.EnableCors(cors);
客户端代码:
//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);
});
只有GetAll功能有效。当我使用POST或DELETE时出现错误消息Cross-Origin-Request被阻止..