2017-05-10 119 views
0

我正在調用API Post方法,但是,我不確定我在做什麼錯誤,但API中的值始終爲空。我從下面調用API的方法。當我碰到這個時,我可以看到Ids是以5個值爲單位的整數列表。PostAsync參數始終爲空

private void Save(List<int> Ids) 
{ 
    var myAPI = ConfigurationManager.AppSettings["MyAPI"]; 

    string myIds = string.Join(",", Ids); 

    using (var client = new HttpClient()) 
    { 

    int result = client.PostAsync(myAPI, new { test = myIds }, new JsonMediaTypeFormatter()) 
         .Result 
         .Content 
         .ReadAsAsync<int>() 
         .Result; 
    } 
} 

我的API簽名是像下面 - 斷點上我可以看到它被擊中,但測試我試圖傳遞參數總是空

[HttpPost] 
    [Route("api/MyController/SaveData")] 
    public HttpResponseMessage SaveData([FromBody]List<string> test) 
    { 
     try 
     { 
     //Rest of method removed for brevity 

我曾試圖消除[ FromBody]從控制器的WebAPI測試,但仍然標註在保存數據API方法得到空與斷點

回答

2

試試這個:

private void Save(List<int> Ids) 
{ 
    var myAPI = ConfigurationManager.AppSettings["MyAPI"]; 

    using (var client = new HttpClient()) 
    { 
     var requestBody = JsonConvert.SerializeObject(Ids); 
     var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json"); 

     var response = client.PostAsync(myAPI, postRequest).GetAwaiter().GetResult(); 
     var rawResponse = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); 
     // Do something with the answer 
    } 
} 

我也建議在該調用之前製作方法private Task Save並用await代替.GetAwaiter().GetResult();

+0

會給出一個去 - 認爲有一個錯誤的答案就在使用_httpClient應該是客戶端我假設 –

+1

你是對的,編輯 –

+0

Web方法簽名必須包含一個參數,然後調用postRequest,並將FromBody必須使用? –