从Angular到.net WebAPI的发布始终为null [英] POSTing from Angular to .net WebAPI is always null
问题描述
我试图将对象从AngularJS发布到MVC 5 WebApi控制器,但该值始终为空
I am trying to Post an object from AngularJS to a MVC 5 WebApi Controller, but the value is always null
我可以在Chrome开发工具中看到可以在请求中找到数据.
I can see in Chrome dev tools that the data can be found on the request.
角度控制器:
$scope.join = function () {
if (!$scope.joinForm.$valid) return;
// Writing it to the server
var payload = $scope.user;
var res = $http.post('/api/some', JSON.stringify( { Data: { payload } }), { header: { 'Content-Type': 'application/json' } });
res.success(function (data, status, headers, config) {
$scope.message = data;
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
MVC 5 API控制器:
MVC 5 API Controller:
public class SomeController : ApiController
{
// POST api/values
public void Post([FromBody]string value)
{
Trace.Write(value);
}
}
如果我将对象包装在{Data:{payload}}
If I wrap my object in {Data: {payload}}
{"Data":{"payload":{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}}}
如果我不包裹它,我会得到:
if I dont wrap it I get:
{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}
(Visual Studio 2015配置为使用IISExpress)
(Visual Studio 2015 is configured to use IISExpress)
有什么想法吗?
推荐答案
value
为null的原因是因为框架的模型绑定程序无法将参数与正文中发送的数据进行匹配帖子的内容.
The reason value
was null is because the framework's model binder was unable to match the parameter to the data that was sent in the body of the post.
创建一个类来存储您的有效载荷
Create a class to store your payload
public class User
{
public string symbol { get; set; }
public int amount { get; set; }
public DateTime startdate { get; set; }
public DateTime enddate { get; set; }
public string interval { get; set; }
}
更新控制器
public class SomeController : ApiController
{
// POST api/post
public void Post(User user)
{
//consume data
}
}
角度控制器
$scope.join = function () {
if (!$scope.joinForm.$valid) return;
// Writing it to the server
var res = $http.post('/api/some', $scope.user, { header: { 'Content-Type': 'application/json' } });
res.success(function (data, status, headers, config) {
$scope.message = data;
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
这篇关于从Angular到.net WebAPI的发布始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!