HttpClient抛出“发送请求时发生错误。”

问题描述 投票:0回答:1

我有三层应用程序体系结构。

我的客户端->我的服务A(REST托管在IIS中)->其他团队的服务X(REST)。

服务A是ASP.Net 4.6.1框架,而不是ASP.Net Core。

客户端正在通过HttpClient与A通信,而A正在通过HttpClient与X通信。

客户端正在向我的服务向A和X发出近2500个呼叫。

在2500个呼叫服务中,随机发生一次(可能是10个呼叫)失败,但以下异常。它不可复制。

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> 
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a 
receive. ---> System.IO.IOException: Unable to read data from the transport connection: An     
established connection was aborted by the software in your host machine. ---> 
System.Net.Sockets.SocketException: An established connection was aborted by the software in your 
host machine
at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags 
socketFlags, AsyncCallback callback, Object state)
at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback 
callback, Object state)
 --- End of inner exception stack trace ---
at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)
at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)
at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace --

这是我的服务电话。 IIS中的A在代码块下面调用,并且每个请求都调用它。 X正在获取用户凭据并根据用户返回数据,因此我们不会在调用之间共享HttpClient。

var user = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;
            System.Security.Principal.WindowsIdentity.RunImpersonated(user.AccessToken, () =>
      {
        static HttpClient Client = new HttpClient();
        static string CallX(string[] args)
        {
            HttpClientHandler handler = new HttpClientHandler
            {
                UseDefaultCredentials = true
            };    

            Client = new HttpClient(handler)
            {
                BaseAddress = new Uri("http://XserviceUrl/api/")
            };
            Client.Timeout = TimeSpan.FromSeconds(600);    
            var result = Client.PostAsync("Fake X controller"
                , new StringContent(JsonConvert.SerializeObject(args)
                , Encoding.UTF8, "application/json")).Result;    

            result.EnsureSuccessStatusCode();

            var json = result.Content.ReadAsStringAsync().Result;
            return DosomethingWithResult(json);    
        }
    });

我尝试过的事情:

一些建议的帖子可能是超时问题。因此,我在客户端和服务A中添加了600秒。我还将IIS请求超时从默认的2分钟更改为10分钟(600秒)。

c# rest asp.net-web-api asp.net-web-api2 httpclient
1个回答
0
投票

如果仅在某些情况下发生,则问题可能与ContentLength有关。因此,最好为以下方法设置ContentLength

result.Content.ReadAsStringAsync(/* if needed also set other parameters */, 
    result.ContentLength);
© www.soinside.com 2019 - 2024. All rights reserved.