简体   繁体   中英

HttpClient - A task was cancelled exception

I usually make a get request from my console application to the api application. Sometimes I encounter the error "A task was canceled" in production environment. But somehow I cannot produce the same error in the development environment.

Error:

    System.Threading.Tasks.TaskCanceledException: A task was canceled.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at WebApiClient.HttpClientExtensions.HttpClientExtension.<>c__DisplayClass5_0`1.<ExecuteGetAsync>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

The code I made a request and encountered the error:

try
{
    var result = await WebApiClient.BuildHttpClient(new Uri("www.domain.com/")).ExecuteGetAsync<string>("requestUrl");

    return result;
}
catch (Exception ex)
{
    throw;
}

My client code:

public class WebApiClient
{
    public static HttpClient BuildHttpClient(Uri baseAddress)
    {
        var client = new HttpClient { BaseAddress = baseAddress };
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }
}

public static partial class HttpClientExtension
{
    public static Task<TResult> ExecuteGetAsync<TResult>(this HttpClient httpClient, string requestUri)
    {
        return Task.Run(() =>
        {
            var response = httpClient.GetAsync(requestUri).Result;
            httpClient.Dispose();

            try
            {
                response.EnsureSuccessStatusCode();
                return response.Content
                    .ReadAsStringAsync()
                    .ContinueWith(jsonTask =>
                    {
                        var json = jsonTask.Result;
                        return JsonConvert.DeserializeObject<TResult>(json);
                    });
            }
            catch (Exception)
            {
                IDictionary data = new Dictionary<string, string>();
                foreach (var httpResponseHeader in response.Headers)
                {
                    data.Add(httpResponseHeader.Key, httpResponseHeader.Value.First());
                }

                throw new HttpRequestFailedException(response.StatusCode.ToString(), data);
            }
        });
    }
}

I was getting same issue recently but when i was trying to making a simple post call with json payload.

Tried passing CancellationToken as null, increased timeout and all different ways of making a post call using httpclient with and without async await but none worked for us.

As a troubleshooting step, used postman and surprisingly it was working all fine with postman , later had compared the request packets which i was sending to the server with postman request packets using wireshark tool and found to be like the request was expecting 100 continue from server which was weird though the request has got nothing more data to send. Suspect was related to content-length in the request being passed as it was expecting 100 continue which we don't have control to.

Using Restsharp nuget library solved the issue for us, though it uses httpclient under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM