调用WebService时task.Wait抛出异常,请求技术排查协助
问题描述
- 调试该问题已超一天,项目即将进入代码冻结阶段,急需解决
- 调用WebService时,在
task.Wait()处抛出异常,未修改过代码但此前运行正常 - 代码要么在
BillingSummaryAPIPortTypeClient()实例化时失败,要么在task.Wait()处失败 - 底层连接已关闭:接收时发生意外错误,InnerException提示:
接收.....的HTTP响应时出错。这可能是由于服务端点绑定未使用HTTP协议,也可能是服务器中止了HTTP请求上下文(可能因服务关闭)。请查看服务器日志获取详细信息。
- StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait() at BillingServiceAPICall.Program.CallPolServiceForData() in C:\VSCollection\POS\Rel_2022_11\Source\BillingServiceAPICall\Program.cs:line 79
配置绑定
<startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="mssqllocaldb" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BillingSummaryAPISoap11Binding"> <security mode="Transport" /> </binding> <!--<binding name="BillingSummaryAPISoap11Binding1" />--> </basicHttpBinding> <customBinding> <binding name="BillingSummaryAPISoap12Binding"> <textMessageEncoding messageVersion="Soap12" /> <httpsTransport /> </binding> </customBinding> <wsHttpBinding> <binding name="WSHttpBinding_IEmailService" messageEncoding="Mtom"> <security mode="Transport" /> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="https://vldv/EmailService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IEmailService" contract="EmailService.IEmailService" name="WSHttpBinding_IEmailService" /> <endpoint address="https://vldev3.ww.com/bc/ws/gw/webservice/BillingSummaryAPI" binding="customBinding" bindingConfiguration="BillingSummaryAPISoap12Binding" contract="BillingService.BillingSummaryAPIPortType" name="BillingSummaryAPISoap12Port"/> </client> </system.serviceModel>
调用BillingSummaryAPI的代码
public static Dictionary<string, double> CallPolServiceForData() { Dictionary<Int32, BResponse> pCallResponse = new Dictionary<int, BResponse>(); Dictionary<Int32, DateTime> pcCallResponseTime = new Dictionary<int, DateTime>(); Dictionary<string, double> pcCallResponseTimeDetails = new Dictionary<string, double>(); List<int?> cancelledPolicies = GetCancelledPoliciesData(); if (cancelledPolicies != null) { foreach (var item in cancelledPolicies) { if (item != null) { int policyNumber = Convert.ToInt32(item); string consoleInfo = policyNumber.ToString(); // to print on console pCallResponse.Add(policyNumber, null); BillingSummaryAPIPortTypeClient client = new BillingSummaryAPIPortTypeClient(); authentication auth = new authentication(); gw_locale l = new gw_locale(); l.Value = "en_US"; auth.username = ConfigurationManager.AppSettings["User"]; auth.password = ConfigurationManager.AppSettings["Pass"]; PolicyInfo info = new PolicyInfo(); info.PolicyNumber = policyNumber.ToString(); try { pcCallResponseTime.Add(policyNumber, DateTime.Now); var task = GetResponse(client, auth, l, info); task.Wait(); var response = task.Result.@return; pcCallResponseTimeDetails[response.PolicyNumber] = DateTime. Now.Subtract(pcCallResponseTime[policyNumber]).TotalSeconds; pCallResponse[policyNumber] = new BResponse() { OutStandingAmount = response.OutstandingAmount, CancellationDate = response.CancellationDate, ExpirationDate=response.ExpirationDate, }; consoleInfo = consoleInfo + " Success"; Console.WriteLine(consoleInfo); } catch (Exception ex) { pcCallResponseTimeDetails[policyNumber.ToString()] = DateTime. Now.Subtract(pcCallResponseTime[policyNumber]).TotalSeconds; pCallResponse[policyNumber] = new BResponse() { ErrorDesc = (ex.InnerException != null) ? ex.InnerException.Message : ex.ToString() }; consoleInfo = consoleInfo + " Error - " + pCallResponse[policyNumber].ErrorDesc; Console.WriteLine(consoleInfo); } } } SaveResultToStg(pCallResponse); } return pcCallResponseTimeDetails; }
排查思路与解决方案
基础连通性排查
- 直接访问服务地址
https://vldev3.ww.com/bc/ws/gw/webservice/BillingSummaryAPI,确认服务是否正常响应(比如返回WSDL页面) - 检查网络环境:是否有代理变更、防火墙规则调整,导致客户端无法访问服务端;测试同一网络下其他机器能否正常调用该服务
- 验证服务端状态:联系运维确认服务是否正常运行,是否有重启、部署或配置变更,查看服务端日志是否有报错记录
绑定与配置问题排查
- 检查SSL/TLS版本兼容性:.NET 4.5.2默认可能不支持TLS 1.2,而服务端可能已禁用旧版本TLS。在客户端代码开头添加强制TLS 1.2的代码:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
- 检查自定义绑定配置:确认
BillingSummaryAPISoap12Binding的httpsTransport是否需要额外配置(比如最大消息大小、超时时间),尝试增加超时时间避免连接被提前关闭:
<httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" timeout="00:10:00" />
- 验证客户端端点配置:确认服务地址、绑定类型、契约名称是否与服务端最新配置一致,尝试重新生成服务引用(Update Service Reference)
代码层面优化
- 避免同步阻塞异步方法:
task.Wait()容易导致死锁或上下文问题,建议将方法改为异步模式,使用await替代Wait():
public static async Task<Dictionary<string, double>> CallPolServiceForData() { // ... 原有代码 var response = (await GetResponse(client, auth, l, info)).@return; // ... 原有代码 }
- 客户端实例管理:在循环中每次创建新的
BillingSummaryAPIPortTypeClient可能导致连接耗尽,建议复用客户端实例或使用using确保资源释放:
using (BillingSummaryAPIPortTypeClient client = new BillingSummaryAPIPortTypeClient()) { // ... 调用服务代码 }
- 增加详细日志:在调用前后记录请求参数、时间戳,捕获更底层的网络异常(比如
WebException),以便定位具体错误原因
证书与安全问题排查
- 检查服务端SSL证书是否过期或不被客户端信任:若服务端使用自签名证书,需将证书导入客户端的信任根证书存储
- 验证身份认证信息:确认
ConfigurationManager.AppSettings["User"]和Pass的取值是否正确,是否有密码过期、权限变更的情况
内容的提问来源于stack exchange,提问作者Ditty
相关产品推荐
相关产品推荐

