【问题标题】:POSTing from Angular to .net WebAPI is always null从 Angular 发布到 .net WebAPI 始终为空
【发布时间】:2016-06-17 20:33:39
【问题描述】:

我正在尝试将 AngularJS 中的对象发布到 MVC 5 WebApi 控制器,但该值始终为空

我可以在 Chrome 开发工具中看到请求中可以找到数据。

角度控制器:

$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 控制器:

public class SomeController : ApiController
{        
    // POST api/values 
    public void Post([FromBody]string value)
    {           
        Trace.Write(value);
    }
}

如果我将对象包装在 {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"}}}

如果我不包装它,我会得到:

{"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)

有什么想法吗?

【问题讨论】:

  • 好吧,一方面,您脚本中的 url 指向的 url 与您在此处为控制器/操作组合提供的 url 不同
  • @DanPantry POST api/some 会命中 SomeController.Post

标签: angularjs asp.net-web-api


【解决方案1】:

value 为 null 的原因是框架的模型绑定器无法将参数与帖子正文中发送的数据匹配。

创建一个类来存储您的有效负载

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 }));
    });
}

【讨论】:

  • 我同意,但这样做还需要简单地发布 $scope.user 原样而不是将其转换为 json 字符串。
  • 我对 Angular 不够熟悉,无法确认这一点。
  • @jbrown,我刚刚检查了$http.post,你是对的。很好,谢谢。
  • 我原来的答案有误,后来更新了。
  • 创建一个类并发布 $scope.user 而不是有效负载对象 :-)
猜你喜欢
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
相关资源
最近更新 更多