【发布时间】:2016-01-18 22:38:06
【问题描述】:
我在 .NET Framework 4.5.2 中使用 HttpClient 类。
我针对第三方 Web 服务调用 PostAsync。 80% 的时间这篇文章有效,20% 的时间我们的回复被缩短了。在这种情况下,我们会得到以下异常:
System.Net.Http.HttpRequestException:将内容复制到 一个流。 ---> System.IO.IOException: Unable to read data from the 传输连接:现有连接被强行关闭 远程主机。 ---> System.Net.Sockets.SocketException:现有的 连接被远程主机强行关闭 System.Net.Sockets.NetworkStream.BeginRead(字节 [] 缓冲区,Int32 偏移量、Int32 大小、AsyncCallback 回调、对象状态)--- 结束 内部异常堆栈跟踪 --- 在 System.Net.Sockets.NetworkStream.BeginRead(字节 [] 缓冲区,Int32 偏移量,Int32 大小,AsyncCallback 回调,对象状态)在 System.Net.FixedSizeReader.StartReading() 在 System.Net.Security._SslStream.StartFrameHeader(Byte[] 缓冲区,Int32 偏移量,Int32 计数,AsyncProtocolRequest asyncRequest)在 System.Net.Security._SslStream.StartReading(字节 [] 缓冲区,Int32 偏移量,Int32 计数,AsyncProtocolRequest asyncRequest)在 System.Net.Security._SslStream.ProcessRead(字节 [] 缓冲区,Int32 偏移量,Int32 计数,AsyncProtocolRequest asyncRequest)在 System.Net.TlsStream.BeginRead(Byte[] 缓冲区,Int32 偏移量,Int32 大小,AsyncCallback asyncCallback,对象 asyncState)在 System.Net.ConnectStream.BeginReadWithoutValidation(字节 [] 缓冲区, Int32 偏移量、Int32 大小、AsyncCallback 回调、对象状态)在 System.Net.ConnectStream.BeginRead(Byte[] 缓冲区,Int32 偏移量,Int32 大小,AsyncCallback 回调,对象状态)在 System.Net.Http.HttpClientHandler.WebExceptionWrapperStream.BeginRead(字节[] 缓冲区、Int32 偏移量、Int32 计数、AsyncCallback 回调、对象 状态)在 System.Net.Http.StreamToStreamCopy.StartRead()
随后的相同请求成功。
我们无法重试此请求,因为已采取业务操作。所以这让我们陷入了尴尬的境地。
这是我的代码:
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = authorizationHeader;
HttpContent httpContent = new StringContent(someXml);
//Exception occurs on next line...
var response = await httpClient.PostAsync("https://thirdpartyendpoint", httpContent);
var responseXml = await response.Content.ReadAsStringAsync();
//convert to Dto
}
第三方服务已成功将记录保存到他们的数据库中,并且在他们的末尾没有看到任何明显的异常。他们确实注意到,失败的请求通常比成功的请求花费更长的时间(大约 18-30 秒)写入数据库。
我能做些什么来更好地处理这个问题?
【问题讨论】:
-
他们的数据库中似乎存在阻塞操作或错误索引。尝试分析数据库查询或监控数据库锁。
-
嗨 Roman,尽管有额外的延迟,但他们并没有在代码中引发异常,而是完成了响应。我们只是没有收到它。
-
他们会检查 HTTP 连接超时。
标签: c# asp.net .net asp.net-web-api