2013-05-13 42 views
7

我想從Web API調用PostAsync方法使用System.Net.Http.HttpClient。我得到以下錯誤:與Web Api的PostAsync HttpClient錯誤 - System.AggregateException「任務被取消。」

System.AggregateException "A task was canceled."

任務:

Id = 1, Status = System.Threading.Tasks.TaskStatus.Canceled, Method = "{null}", Result = "{Not yet computed}"

代碼:

using (HttpClientHandler handler = new HttpClientHandler()) 
{ 
    handler.Credentials = new NetworkCredential("MyUsername", "[email protected]"); 

    using (HttpClient client = new HttpClient(handler)) 
    { 
     var postData = new List<KeyValuePair<string, string>>(); 
     postData.Add(new KeyValuePair<string, string>("status", "Hello world")); 

     HttpContent content = new FormUrlEncodedContent(postData); 

     var responseTask = client.PostAsync(url, content).ContinueWith(
      (postTask) => 
      { 
       postTask.Result.EnsureSuccessStatusCode(); 
      }); 
    } 

我假設responseTask將強制方法來同步運行?

這是一個WPF應用程序,而不是ASP.NET。

回答

3

在調試,你可以嘗試寫一個擴展方法來獲取除外條款:

public static HttpResponseMessage PostAsyncSafe(this HttpClient client, string requestUri, string content) 
     { 
      var requestContent = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"); 
      return PerformActionSafe(() => (client.PostAsync(requestUri, requestContent)).Result); 
     } 

public static HttpResponseMessage PerformActionSafe(Func<HttpResponseMessage> action) 
     { 
      try 
      { 
       return action(); 
      } 
      catch (AggregateException aex) 
      { 
       Exception firstException = null; 
       if (aex.InnerExceptions != null && aex.InnerExceptions.Any()) 
       { 
        firstException = aex.InnerExceptions.First(); 

        if (firstException.InnerException != null) 
         firstException = firstException.InnerException; 
       } 

       var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
       { 
        Content = 
         new StringContent(firstException != null 
              ? firstException.ToString() 
              : "Encountered an AggreggateException without any inner exceptions") 
       }; 

       return response; 
      } 
     } 
0

不同步,第二個任務也將被執行異步但與第一個任務鏈接,因此只有在第一個任務執行後。

似乎是第一項任務 - PostAsync執行時出錯。嘗試從AggregateException 趕上TPL聚集異常,發現在內部異常集合的詳細信息。例如像here或訂閱TaskScheduler.UnobservedTaskException和記錄有你所有的例外

10

我得到這個相同的錯誤,並跟蹤到我的HttpClient超時。默認的超時時間是100秒。我將以下內容添加到HttpClient的創建中。

HttpClient httpClient = new HttpClient(); 
httpClient.Timeout = TimeSpan.FromMinutes(10);