Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostAsync HttpClient error with Web Api - System.AggregateException "A task was canceled."

I'm trying to call PostAsync method using System.Net.Http.HttpClient from the Web API. I get the following error:

System.AggregateException "A task was canceled."

Task:

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

Code:

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();
            });
    }

I assume the responseTask will force the method to run synchronously?

It's a WPF application, not ASP.NET.

like image 817
pfeds Avatar asked May 13 '13 08:05

pfeds


People also ask

What is Httpclient PostAsync?

PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.

What is AggregateException C#?

AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query.


2 Answers

I was getting this same error and tracked it down to my HttpClient was timing out. The default timeout is 100 seconds. I added the following to the create of the HttpClient.

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

like image 84
Ron Avatar answered Oct 17 '22 15:10

Ron


In terms of debugging you could try writing an extension method to get the exception:

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;
            }
        }
like image 4
Joanna Derks Avatar answered Oct 17 '22 14:10

Joanna Derks