调用第三方WebService传byte[]文件时遇连接强制关闭异常求助
异常现象
对接第三方WebService时,仅涉及文件上传(参数为byte[])的AddRequestDocumentAsync方法调用失败,其余方法均可正常执行,具体报错信息如下:
An error occurred while receiving the HTTP response to https://someaddress/Services/DefineMerchant.
This could be due to the service endpoint binding not using the HTTP protocol.
This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
The underlying connection was closed: An unexpected error occurred on a receive.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
An existing connection was forcibly closed by the remote host
现有代码与配置
调用代码
using (var client = new SomeService.DefineMerchantsClient()) { client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; client.ClientCredentials.UserName.UserName = "*****"; client.ClientCredentials.UserName.Password = "****"; var response = await client.AddRequestDocumentAsync(new MarketerDocEntity { File = requestData.File, DocumentType = requestData.DocumentType, DocumentTrackingCode = requestData.DocumentTrackingCode }); }
App.config配置(.NET Framework 4.7.2控制台应用)
<system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IDefineMerchants" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="TransportWithMessageCredential" /> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="https://someaddress/Services/DefineMerchant" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDefineMerchants" contract="SomeService.IDefineMerchants" name="BasicHttpBinding_IDefineMerchants"/> </client> </system.serviceModel> <system.web> <httpRuntime maxRequestLength="2147483647" executionTimeout="103600"/> </system.web>
已尝试的无效操作
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
问题定位与解决建议
该异常本地配置和服务端问题均有可能,可按以下顺序排查:
优先排查本地配置调整
添加发送超时设置
大文件上传耗时较长,当前配置未设置发送超时,可能触发连接被强制关闭。在basicHttpBinding的binding节点中添加:sendTimeout="00:10:00"可根据实际文件大小调整超时时长(示例为10分钟)。
启用流式传输模式
默认的缓冲模式可能因一次性发送过大请求导致异常,建议启用流式传输。在binding节点添加:transferMode="Streamed"注意:流式模式下
maxBufferSize会被忽略,需确保服务端支持该传输模式。确认Keep-Alive配置
显式开启HTTP长连接,避免传输过程中连接中断。在<security>节点下添加:<transport keepAliveEnabled="true"/>
服务端可能存在的问题
文件大小限制
即使本地设置了超大消息容量,服务端可能存在独立的上传限制(比如IIS的maxAllowedContentLength,单位为字节),需联系第三方排查服务端相关配置。服务端资源或超时限制
大文件处理可能占用过多服务端资源(内存、CPU),或服务端超时设置过短,导致主动关闭连接。需第三方查看服务端日志确认具体原因。TLS层兼容性问题
虽然其他方法正常,但大文件传输可能触发TLS层异常,比如服务端不支持当前协商的TLS版本,或证书链存在隐式检查逻辑。
总结
先通过调整本地配置(添加超时、启用流式传输)尝试解决,若无效则必须联系第三方查看服务端日志,确认是否为服务端的大小限制、资源不足或超时设置导致的连接强制关闭。
内容的提问来源于stack exchange,提问作者Nima Masghadi

