3

I have the similar code in my C# Windows application.

public async Task<HttpResponseMessage> SendHttpRequest()
{
    HttpResponseMessage response = null;
    try
    {
        HttpClient client = new HttpClient();
        string accessToken = await GetBearerToken(resourceUrl, clientId, clientSecret, tokenProviderUrl);
        if (!string.IsNullOrEmpty(accessToken))
            httpRequest.Headers.Add("Authorization", ("Bearer " + accessToken));

        response = await client.SendAsync(httpRequest);
    }
    catch(Exception ex)
    {
        log.Error("Exception raised while sending HTTP request");
        log.Error("Exception details : " + ex.Message);
    }           

    return response;
}

public async Task<string> GetBearerToken()
{           
    HttpResponseMessage response = null;
    HttpClient client = new HttpClient();
    string token = "";
    try
    {
        var request = new HttpRequestMessage(HttpMethod.Post, tokenProviderUrl);
        request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
            { "client_id",clientId},
            { "client_secret", clientSecret },
            { "grant_type", "client_credentials" },
            { "resource", resource },
        });

        response = await client.SendAsync(request);                
        var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
        token = payload.Value<string>("access_token");                
    }
    catch (HttpRequestException ex)
    {
        log.Error("Error in GetToken : " + ex.Message.ToString());
    }
    return token;
}

The above code works perfectly fine for most the times. But once in a while it throws an exception saying "Task was Cancelled". So according to few questions and articles , I figured out that there can be 2 reasons for this.

  1. Request Timeout.
  2. Or request was actually cancelled.

I have checked this variable: CancellationToken.IsCancellationRequested. It returned false. So I'm assuming it is Timeout issue. To base this timeout, I have also checked the time difference between the request started and exception thrown. It is exactly 100 seconds (which is default time of httpClient).

Now when I retry the same request immediately after 5-10 seconds, it is returning success.As this issue is not occurring for every request, I'm bit confused as to what is happening.

The same request executed successfully 95% of the times and rest 5% of the times, it says Task was cancelled.

Is there any scenario where the same Task is executed once and cancelled once.

I have send request through Postman for the Web API and not once I received this issue. It is only through Windows app I'm facing this.

Is there anything am I missing?

Edit

Inner Exception is null.

Stack Trace : at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpClient.d__58.MoveNext() --- 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()

halfer
  • 19,824
  • 17
  • 99
  • 186
CrazyCoder
  • 2,194
  • 10
  • 44
  • 91

1 Answers1

0

you shouldn't make a new HttpClient everytime you want to post. make a new HttpClient in your main method and just pass it in your "SendHttpRequest". I had similar issiues with Task canceling so I searched some and used this. it worked for me

HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        client.DefaultRequestHeaders.Add("Keep-Alive", "false");
        client.Timeout = TimeSpan.FromMinutes(20);
Shift
  • 1