[英]Values received via http post are null with AngularJS and Web api 2
I followed a tutorial and wanted to expand the functionality of already existing code. 我按照教程,想要扩展已有代码的功能。 Code: https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA
代码: https : //send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA
It's using angularJS as the frontend and webapi 2 aspnet with entitiyframework. 它使用angularJS作为前端和webapi 2 aspnet with entitiyframework。 The problem is that my http posts are sending null values.
问题是我的http帖子正在发送空值。 I am guessing I have to post it in the right format, but im not sure how exactly to do it.
我猜我必须以正确的格式发布它,但我不确定如何做到这一点。
I tried transforming it into an object but it still received as null. 我尝试将它转换为一个对象,但仍然收到null。
controller.js controller.js
function save(contact) {
var deferred = $q.defer();
$http.post('/api/Contact/' + contact).success(function (results) {
$scope.contact = results;
deferred.resolve(results);
}).error(function (data, status, headers, config) {
deferred.reject('Failed saving contact');
});
return deferred.promise;
};
fails at db.Contacts.Add(Contact); 在db.Contacts.Add(联系人)失败; (null error)
(null错误)
public HttpResponseMessage Post([FromBody] Contact Contact)
{
if (ModelState.IsValid)
{
Console.Write("post contact");
Console.Write(Contact);
db.Contacts.Add(Contact);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Contact);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Contact.Id }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
Tried sending this: 试过发送这个:
{Name: "test", Address: "test", City: "teee", Country: "tesd"}
Edit: 编辑:
After trying to save the contact with the save
function: 尝试使用
save
功能保存联系人后:
output of console log Request URL: http://localhost:64158/api/Contact/[object%20Object] 控制台日志的输出请求URL: http:// localhost:64158 / api / Contact / [object%20Object]
If i open the [object%20Object] in a new tab from the network view i get this: 如果我从网络视图中打开新选项卡中的[object%20Object],我得到:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'SampleEF6.Models.Contact Get(Int32)' in 'SampleEF6.Controllers.ContactController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
You're sending the data wrong. 您发送的数据有误。 You're supposed to send the data (contact in this example) in the body of the request, instead of the url.
您应该在请求正文中发送数据(本示例中的联系人),而不是url。
Try $http.post('/api/Contact/', contact)
试试
$http.post('/api/Contact/', contact)
https://docs.angularjs.org/api/ng/service/$http#post https://docs.angularjs.org/api/ng/service/$http#post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.