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

标签 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]

如果我在 WebView 的新选项卡中打开 [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

关于c# - 通过 http post 接收的值对于 AngularJS 和 Web api 2 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57094864/

相关文章:

javascript - 在 Jasmine 2.0 中测试 AngularJS promise

javascript - 如何在数据库和 Firebase 身份验证系统之间链接数据

c# - 当找到路由/url但没有找到它背后的资源时返回什么?

c# - 在 ASP.NET Core 中访问当前的 HttpContext

c# - 单声道错误格式异常但不是在 Windows 上

javascript - JS : Dict of arrays combining by AND operation

c# - 带有响应 header 的单元测试 webapi Controller

c# - ASP.net Identity UserManager 不验证密码

C# 数组索引总是超出

c# - Visual C# 速成版中的 Rss 阅读器