2015-11-13 81 views
2

角代码:AngularJs邮政的WebAPI总是空

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" 
         }), 

没有骰子。

我在做什么错?

+0

你为什么要使用一个帖子?看起来你想要一个get。 – jbrown

+0

这是客户真正的问题吗?任何服务器端Web框架都应该可以访问数据正文。你在这里建立了什么服务器。 –

+0

@jbrown不,您不想使用获取用户名和密码的请求! –

回答

1

附上您在$ .PARAM()数据

例子:

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

+2

不是每个人都可以在他们的项目中访问或者需要jQuery。我相信你也可以使用请求变换器。 http://stackoverflow.com/a/1714899/1784301 –

+0

是的,我的解决方案是完美的,如果你使用jQuery,它使得它很容易实现。或者如果你不想使用jquery,你可以参考Sean Larkin的链接。 – amanpurohit

+1

@amanpurohit,你的方法将解决这个问题,但增加一个额外的依赖。但是你的回答肯定会对很多人有所帮助。 – w2olves

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的参数(在另一个答案中建议)参数 。很公平。您需要 自己从请求流中获取并处理它。