HttpClient请求有时在C#中失败 [英] HttpClient request failing sometimes in c#

查看:511
本文介绍了HttpClient请求有时在C#中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的c#Windows应用程序中有类似的代码.

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

上面的代码在大多数情况下都能正常工作.但是有时会抛出一个异常,说任务已取消".因此,根据一些问题和文章,我发现可能有两个原因. 1.请求超时.
2.或请求实际上已取消.

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.

我已经检查了此变量-CancellationToken.IsCancellationRequested.它返回false.所以我假设这是超时问题.为了使此超时成为基础,我还检查了启动请求和引发异常之间的时间差.恰好是100秒(这是httpClient的默认时间).

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

现在,当我在5到10秒后立即重试相同的请求时,它会返回成功.由于并非每个请求都出现此问题,所以我对正在发生的事情感到有些困惑.

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.

同一请求成功执行了95%,其余5%成功,它说任务已取消.

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.

我已经通过邮递员发送了有关Web API的请求,但是没有收到此问题.我只能通过Windows应用程序来解决这个问题.

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

编辑

内部异常为null.

Inner Exception is null.

堆栈跟踪:位于 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Net.Http.HttpClient.d__58.MoveNext() ---从上一个引发异常的位置开始的堆栈跟踪--- System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务),位于System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

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

推荐答案

您不应在每次要发布时都新建一个HttpClient. 在您的主要方法中创建一个新的HttpClient,然后将其传递给您 "SendHttpRequest". 我在取消任务时也遇到了类似的问题,所以我搜索了一些问题并使用了它. 对我有用

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

这篇关于HttpClient请求有时在C#中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆