0

I have the following code to fetch the bearer token and then call the Web API in a c# 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 problem I'm facing here is,some times , this code throws an exception saying "Task was cancelled" once in a while and not everytime. I have searched online and came across this answer.So I have checked if the task was being cancelled.Then I increased the Timeout to 30 minuties as mentioned in that answer.

Now the strange thing is, the task waits for 30 mins (or whatever timeout we have specified) and then throws Task was cancelled exception.This is driving me crazy.

I want to know why is the Task getting cancelled when we are not requsting for it explicitly and who or from where the task is getting cancelled? Is there any way to find the source of the cancellation request?

Any help in this regard is highly appreciated as I'm unable to figure out the issue.

Please assume that all the variables have correct values though it is not mentioned here.

EDIT

Exception Message :

A task was canceled.

This is the Exception Stack Trace :

Exception StackTrace : 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() at SampleProject.d__2.MoveNext() in C:\Users\SampleProject\HttpHelper.cs:line 145 --- End of stack trace from previous location where exception was thrown ---

CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • could you please try use application insights to monitor your app? It may record some useful info, maybe can find the cause. – Ivan Glasenberg Nov 02 '18 at 06:58
  • *Don't* create HttpClient all the time, create one instance and reuse it. As for the exception, where is it? Post the *full* exception in the question, as returned by `Exception.ToString()`. This contains the call stack and any inner exceptions. A 30 minute timeout though suggests there's something wrong with the code or the server. Increasing the timeout just covers up the problem, it doesn't solve it – Panagiotis Kanavos Nov 02 '18 at 07:53
  • @PanagiotisKanavos I have included the Exception details in the question.Inner exception was blank. – CrazyCoder Nov 02 '18 at 08:52
  • Post the full exception, not just the parts you think are important – Panagiotis Kanavos Nov 02 '18 at 09:13
  • What is that `.TaskAwaiter\`1.GetResult()` ? You are *blocking* the asynchronous call? What is at `HttpHelper.cs` line 145? It's definitely not the code you posted here. Most likely you are deadlocking your own code by blocking the async call instead of awaiting it – Panagiotis Kanavos Nov 02 '18 at 09:15
  • At line 145, this is the line response = await client.SendAsync(httpRequest); – CrazyCoder Nov 02 '18 at 09:34

0 Answers0