在AngularJS和Web API 2中,通过http发布接收的值为null

时间:2019-07-18 12:49:46

标签: c# angularjs asp.net-web-api2 http-post

我遵循了一个教程,想扩展现有代码的功能。代码:https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA

它使用angularJS作为前端,并使用带有entitiyframework的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>

1 个答案:

答案 0 :(得分:2)

您发送的数据有误。您应该在请求的正文中发送数据(在此示例中为联系人),而不是在网址中发送电子邮件。

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

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