2016-04-05 18 views
0

我使用的是angularjs,我試圖對我的web api進行HttpPost調用。web api 2發佈參數 - 必須使用json.stringyfi

我的API方法:

[HttpPost] 
    [Route("authentication/getkey")] 
    public IHttpActionResult GetKey([FromBody]string password) { 
     //Do stuff 
    } 

我的電話:

service.getKey = function (password) { 
      return $http.post('api/authentication/getkey', JSON.stringify(password)) 
       .then(function(result) { 
        return result.data; 
       }); 
     } 

現在這工作得很好,但我真的需要使用JSON.stringify?我試着像下面這樣發送它,但是它們都是password = null。我必須使用JSON.stringify還是我在其他示例中做錯了?

//Doesnt work 
service.getKey = function (password) { 
    return $http.post('api/authentication/getkey', password) 
     .then(function(result) { 
      return result.data; 
     }); 
    } 

//Doesnt work 
service.getKey = function (password) { 
    return $http.post('api/authentication/getkey', {password}) 
     .then(function(result) { 
      return result.data; 
     }); 
    } 
+0

您需要將POST請求中的數據作爲JSON格式發送,因爲默認情況下角$ http服務將Content-Type作爲application/json發送。 JSON.stringify會將您的數據轉換爲JavaScript對象表示法(JSON)字符串。有沒有你不想使用JSON.stringify的原因?一種方法是更改​​內容類型。如果你願意,我可以提供一些示例代碼。 –

+0

@VivekN請做那個。我只想看看如何去做的其他例子 - 或者我該怎麼做 – MrProgram

回答

2

想要使用JSON.stringify,另一種選擇是將數據發送爲application/x-www-form-urlencoded,正如其他答案中指出的那樣。這樣您就可以將數據作爲表單數據發送。我不確定$ http.post Shortcut方法的語法,但這個想法是一樣的。

service.getKey = function (password) { 
    $http({ 
      method: 'POST', 
      url: 'api/authentication/getkey', 
      data: $.param({ '': password }), 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      } 
     }) 
.then(function(result) { 
      return result.data; 
     }); 
2

從Microsoft的Web API官方文檔大約Parameter Binding in ASP.NET Web API

當有一個參數[FromBody],網絡API使用Content-Type頭,選擇格式化。在這個例子中,內容類型是「application/json」,而請求主體是一個原始的JSON字符串(不是JSON對象)。

$http服務在POST請求發送Content-Type: application/json作爲頭默認情況下,你可以從official docs看,所以網絡API試圖用他的JsonFormatter您的請求主體進行綁定。正因爲如此,你必須爲他提供一個格式良好的Json字符串(不是帶有字符串的Json對象)才能正確綁定他的原始字符串參數。

作爲一個側面說明,你也可以發送郵件使用application/x-www-form-urlencoded作爲Content-Type頭的請求,但當時如果不這樣做,你將有你的身體格式化爲形式參數(使用類似於jQuery的$.param(..)東西)