How to know from which point HttpClient task cance

2019-08-26 22:16发布

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 ---

0条回答
登录 后发表回答