从Angular到.net WebAPI的发布始终为null

编程入门 行业动态 更新时间:2024-10-22 15:40:46
本文介绍了从Angular到 WebAPI的发布始终为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

本文发布于:2023-10-11 23:17:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:net   Angular   null   WebAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!