.NET Framework 4.5 WebService调用超时:如何延长客户端超时时间?
解决.NET Framework 4.5中WebService调用5分钟超时问题
问题根源
你遇到的固定5分钟超时,是因为.NET调用WebService默认基于WCF的BasicHttpBinding,其底层依赖的HttpWebRequest默认超时为5分钟,这个超时优先级高于你配置的OperationTimeout、绑定的sendTimeout/receiveTimeout。
有效解决方案
1. 全局配置HttpWebRequest超时(通过app.config)
在app.config的<configuration>节点下添加<system.net>配置,覆盖默认的5分钟超时:
<system.net> <settings> <httpWebRequest> <!-- 设置超时为15分钟(单位:毫秒) --> <requestTimeout>900000</requestTimeout> <servicePointManager expect100Continue="false" /> </httpWebRequest> </settings> </system.net>
2. 代码中针对特定服务设置超时
在创建WebService客户端实例前,直接修改对应服务地址的ServicePoint超时参数:
// 替换为你的WebService实际地址 Uri serviceUrl = new Uri("http://your-service-url/YourWebService.asmx"); ServicePoint servicePoint = ServicePointManager.FindServicePoint(serviceUrl); // 设置连接超时和空闲超时为15分钟 servicePoint.ConnectionTimeout = 900000; servicePoint.MaxIdleTime = 900000; // 后续创建客户端的代码不变 using (WebService.WebServiceClient client = new WebService.WebServiceClient()) { // ... 你的原有代码 }
3. 确保绑定配置与客户端匹配
检查app.config中endpoint是否正确引用了你的绑定配置,避免配置未生效:
<system.serviceModel> <bindings> <basicHttpBinding> <binding name="WebServiceClient" closeTimeout="00:15:00" openTimeout="00:15:00" receiveTimeout="00:15:00" sendTimeout="00:15:00"> <!-- 其他绑定参数 --> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://your-service-url/YourWebService.asmx" binding="basicHttpBinding" bindingConfiguration="WebServiceClient" <!-- 必须与绑定名称一致 --> contract="WebService.IWebService" /> </client> </system.serviceModel>
4. 代码中直接构建绑定(替代配置文件)
如果配置文件方式未生效,可以在代码中直接创建绑定并设置超时参数,再传入客户端构造函数:
// 创建绑定并设置超时 BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMinutes(15); binding.ReceiveTimeout = TimeSpan.FromMinutes(15); binding.OpenTimeout = TimeSpan.FromMinutes(15); binding.CloseTimeout = TimeSpan.FromMinutes(15); // 传入绑定和服务地址创建客户端 using (WebService.WebServiceClient client = new WebService.WebServiceClient( binding, new EndpointAddress("http://your-service-url/YourWebService.asmx"))) { client.ClientCredentials.UserName.UserName = wsUsername; client.ClientCredentials.UserName.Password = wsPassword; using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes( $"{client.ClientCredentials.UserName.UserName}:{client.ClientCredentials.UserName.Password}")); httpRequestProperty.Headers["key"] = apiKey; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; client.WebServiceFunction(); } }
注意事项
OperationTimeout是整个服务调用的总超时,而底层HttpWebRequest的超时会限制这个值,所以必须覆盖前者的默认5分钟设置。- 服务端已设置10分钟超时,客户端超时设置建议不超过服务端值(比如设为10分钟),避免无效等待。
内容的提问来源于stack exchange,提问作者Matko
相关产品推荐
相关产品推荐

