2017-01-18 49 views
2

雖然我發佈請求到其餘api程序將崩潰和線程被中止將發生。 請指教。線程被中止問題在httpClient.PostAsync

public async Task<TResponse> Post<TRequest, TResponse>(string method, TRequest request) 
    { 
      JsonMediaTypeFormatter jsonFormat = new JsonMediaTypeFormatter 
      { 
       SerializerSettings = 
       { 
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, 
        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, 
        PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None 
       } 
      }; 

      var response = await _httpClient.PostAsync(_baseUrl + method, request, jsonFormat); 
      var finalResponse = await response.Content.ReadAsAsync<TResponse>(); 

      return finalResponse; 
    } 

請注意,沒有請求將被髮送到服務器。順便_httpClient將被定義爲以下

 _httpClient = 
      new HttpClient(new HttpClientHandler 
       { 
        AutomaticDecompression = 
         System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate 
       }) 
       {Timeout = TimeSpan.FromSeconds(50)}; 
     _httpClient.DefaultRequestHeaders.Add("Authorization", "apikey " + apiKey); 

回答

2

我有數字,這也使我自己,原來,PostAsync將調用其取消當前線程一些其他的方法。所以我刪除了await關鍵字並獲得最終結果。

var response = _httpClient.PostAsync(_baseUrl + method, request, jsonFormat).Result;