从angularjs向webAPi发送post请求时,参数为null

时间:2015-09-07 11:11:22

标签: javascript c# json angularjs asp.net-web-api2

我试图调用一个方法,但参数显示为null

服务器端代码

[HttpPost]
        public IHttpActionResult PostRule(ActionRuleParameter actionRule)
        {
            // SOME CODE               
            return BadRequest();
        }

        public class ActionRuleParameter
        {
            public string action;
            public string rule;
        }

客户端代码

addRule: function ($scope) {
            //var data = { "action": "post", "rule": { "ID": "1", "Name": "Ramesh", "PassFail": "Pass" } }

            var data1 = { "action": "post","rule":"rule" };


            $http({
                url: urlContent + '/api/Rules',
                method: "POST",
                data: { "actionRule": data1 }
            }).success(function (response) {
                $scope.rules = response;
            });;
        },

actionrule将显示为null。

2 个答案:

答案 0 :(得分:1)

您需要在参数

之前添加[FromBody]
    public IHttpActionResult PostRule([FromBody]ActionRuleParameter actionRule)
    {
        // SOME CODE               
        return BadRequest();
    }

答案 1 :(得分:0)

我使用Angular和新的ASP.NET堆栈来解决这个问题。添加[FromBody]为我修复了它,请尝试:

 [HttpPost]
 public IHttpActionResult PostRule([FromBody]ActionRuleParameter actionRule)
 {
     // SOME CODE               
     return BadRequest();
 }