【发布时间】:2019-07-18 12:49:46
【问题描述】:
我遵循了一个教程并希望扩展现有代码的功能。代码:https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA
它使用 angularJS 作为前端和带有实体框架的 webapi 2 aspnet。问题是我的 http 帖子正在发送空值。我猜我必须以正确的格式发布它,但我不确定该怎么做。
我尝试将它转换为一个对象,但它仍然接收为 null。
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;
};
db.Contacts.Add(Contact) 失败; (空错误)
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);
}
}
尝试发送这个:
{Name: "test", Address: "test", City: "teee", Country: "tesd"}
编辑:
尝试使用save 函数保存联系人后:
output of console log 请求网址:http://localhost:64158/api/Contact/[object%20Object]
如果我从网络视图的新选项卡中打开 [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>
【问题讨论】:
-
请使用 Chrome 开发者工具中的网络标签。请与我们分享发布到的确切 url。并且 exact 有效载荷正在发布。
-
当代码在 JS 中运行时,
contact的 exact 值是多少?console.log这是肯定的。 -
我添加了更多信息。我猜网址中的内容不正确?
标签: c# angularjs asp.net-web-api2 http-post