2013-05-13 357 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);