Skip to main content
 首页 » 编程设计

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

2024年02月25日30arxive

我学习了教程并希望扩展现有代码的功能。代码: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