通过 http post 接收的值对于 AngularJS 和 Web api 为空 2

Values received via http post are null with AngularJS and Web api 2

我学习了教程并希望扩展现有代码的功能。代码:https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA

它使用 angularJS 作为前端和带有 entitiyframework 的 webapi 2 aspnet。问题是我的 http posts 正在发送空值。我猜我必须以正确的格式 post 它,但我不确定该怎么做。

我尝试将它转换为一个对象,但它仍然收到 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(联系人)处失败; (空错误)

        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 请求 URL: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>

您发送的数据有误。您应该在请求正文中发送数据(本例中为联系人),而不是 url.

尝试$http.post('/api/Contact/', contact)

https://docs.angularjs.org/api/ng/service/$http#post