9

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

System.AggregateException “任务已取消。”

任务:

Id = 1,状态 = System.Threading.Tasks.TaskStatus.Canceled,方法 =“{null}”,结果 =“{尚未计算}”

代码:

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。

4

3 回答 3

10

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

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

于 2014-11-14T13:58:31.650 回答
4

在调试方面,您可以尝试编写扩展方法来获取异常:

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;
            }
        }
于 2013-05-13T10:55:55.080 回答
0

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

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

于 2013-05-13T09:25:17.267 回答