2015-11-13 80 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的參數(在另一個答案中建議)參數 。很公平。您需要 自己從請求流中獲取並處理它。