HttpClient request failing sometimes in c#

≡放荡痞女 提交于 2019-12-10 22:09:24

问题


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.Any help is highly appreciated.Thanks

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


回答1:


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


来源:https://stackoverflow.com/questions/53150544/httpclient-request-failing-sometimes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!