Web Api的PostAsync HttpClient错误 - System.AggregateException“任务已取消。”

时间:2013-05-13 08:15:21

标签: c# asp.net-web-api httpclient wcf-web-api asynchttpclient

我正在尝试使用Web API中的System.Net.Http.HttpClient调用PostAsync方法。我收到以下错误:

  

System.AggregateException“任务已取消。”

任务:

  

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

代码:

using (HttpClientHandler handler = new HttpClientHandler())
{
    handler.Credentials = new NetworkCredential("MyUsername", "p@ssw0rd");

    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 个答案:

答案 0 :(得分:10)

我收到了同样的错误,并将其追踪到我的HttpClient超时。默认超时为100秒。我在HttpClient的创建中添加了以下内容。

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

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

答案 1 :(得分: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;
            }
        }

答案 2 :(得分:0)

不同步,第二个任务也将执行异步但与第一个任务链接,因此仅在第一个任务执行后执行。

似乎是第一个任务 - PostAsync执行时出错。尝试捕获TPL聚合异常并在AggregateException内部异常集合中查找更多详细信息 例如,如here或订阅TaskScheduler.UnobservedTaskException并记录所有例外情况