2017-10-19 123 views
1

我想在一個C#應用程序中調用多個服務。來自一項服務的響應作爲輸入參數傳遞給其他服務。作爲響應第一個服務是一個數字數組,調用其他服務在for循環中像下面從C#應用程序調用多個Web服務

public async Task<IHttpActionResult> Get() 
{ 
...... 
var response = await iLab_client.GetAsync(uri_serviceid); 
var datafile = await response.Content.ReadAsStringAsync(); 
var returnDataObj = JsonConvert.DeserializeObject<Models.ReqDTO.RootObject>(datafile); 
foreach (var req in returnDataObj.il_response.svc_req) 
{ 
    int request_id = req.id; 

    //Calling the other service passing the input parameter 

    using (var iLab_client_request = new HttpClient()) 
    { 
    string request_Uri = BaseURL_iLab + "svc_req/"+request_id+"/c_forms.json"; 
    Uri uri_request = new Uri(request_Uri); 
    client_request.BaseAddress = uri_request; 
    client_request.DefaultRequestHeaders.Accept.Clear(); 
    client_request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    client_request.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); 
    var request_response = await client_request.GetAsync(uri_request); 
    var responsefile = await request_response.Content.ReadAsStringAsync(); 
    var request_returnDataObj = JsonConvert.DeserializeObject<Models.DTO.RootObject>(responsefile); 
    return Ok(request_returnDataObj); 
    }}} 

它trows錯誤說'GetResponseFromiLabAPIController.Get()': not all code paths return a value我明白,我需要創建可以使用存儲響應的對象Add()和從for循環外部返回它。但我不確定應該存儲哪些對象類型,可以存儲來自每個服務調用的所有響應。

回答

0

您可以將回復存儲在列表中。

public async Task<List<IHttpActionResult>> Get() 
{ 
    ...... 

    var responses = new List<IHttpActionResult>>(); 
    var response = await iLab_client.GetAsync(uri_serviceid); 
    var datafile = await response.Content.ReadAsStringAsync(); 
    var returnDataObj = JsonConvert.DeserializeObject<Models.ReqDTO.RootObject>(datafile); 
    foreach (var req in returnDataObj.il_response.svc_req) 
    { 
     int request_id = req.id; 

     //Calling the other service passing the input parameter 

     using (var iLab_client_request = new HttpClient()) 
     { 
      string request_Uri = BaseURL_iLab + "svc_req/"+request_id+"/c_forms.json"; 
      Uri uri_request = new Uri(request_Uri); 
      client_request.BaseAddress = uri_request; 
      client_request.DefaultRequestHeaders.Accept.Clear(); 
      client_request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
      client_request.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); 
      var request_response = await client_request.GetAsync(uri_request); 
      var responsefile = await request_response.Content.ReadAsStringAsync(); 
      var request_returnDataObj = JsonConvert.DeserializeObject<Models.DTO.RootObject>(responsefile); 
      responses.Add(request_returnDataObj); 
     } 
    } 
    return responses; 
} 
相關問題