AngularJs Post to WebApi始终为null

时间:2015-11-13 17:00:19

标签: angularjs asp.net-mvc asp.net-web-api2

Angular Code:

 getAuthorizationStatus: function () {
                    var deferred = $q.defer();
                     $http({
                        method: "POST",
                        url: url,
                        data: {
                            username: $scope.username,
                            password: $scope.password
                        },
                        contentType: 'application/json',
                        headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    }
                    }).success(deferred.resolve)
                      .error(deferred.reject);
                    return deferred.promise;
                },

我的服务器端代码:

  [HttpPost]
        public int ValidateUser([FromBody]Credentials credentials)
        {
            try
            {
                string username = credentials.username;
                string password = credentials.password;
          //Do stuff
        }
        catch (Exception ex)
        {
            throw ex;
            return -1;
        }

        return -1; // not valid user
    }

我遇到的问题是我能够点击Api方法,但里面的数据总是为空。我尝试了几种这样的组合:

  data:  JSON.stringify({
                            "username" : "username",
                            "password":"mypassword"
                        }),

没有骰子。

我做错了什么?

3 个答案:

答案 0 :(得分:1)

将您的数据包含在$ .param()

示例:

data: $.param({ username: $scope.username,password: $scope.password })

答案 1 :(得分:1)

我会尝试更改$http POST的默认和适当行为,而是让服务器从正确的位置读取数据。取自MVC controller : get JSON object from HTTP body?

[HttpPost]
public ActionResult Index(int? id)
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();

    InputClass input = null;
    try
    {
        // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
        input = JsonConvert.DeserializeObject<InputClass>(json)
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //do stuff

}
  

事实证明,MVC并没有真正将POST主体绑定到任何身体   特别的课程。你也不能把POST主体作为一个参数获取   ActionResult(在另一个答案中建议)。很公平。你需要   自己从请求流中获取它并处理它。

答案 2 :(得分:0)

在动作输入参数旁边使用[FromBody]足以从请求中获取数据。您的问题是您通过content-type在Angular代码中覆盖了headers

contentType: 'application/json',
headers: {
   'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}

必须为'application / json'才能发送json数据。只需删除该标头,它就可以正常工作。

相关问题