.NET Core默认绑定调用Web服务TransportBindingElement错误修复
问题描述
在.NET Core 7项目中调用Web服务时无法访问服务,调用方法时抛出错误:
契约为“IMyService”的ServiceEndpoint上的CustomBinding缺少TransportBindingElement。每个绑定必须至少有一个派生自TransportBindingElement的绑定元素。
服务引用使用默认绑定,尝试重写客户端配置但未生效,配置代码如下:
private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(TimeSpan timeout) { var httpsBinding = new BasicHttpsBinding(); httpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; httpsBinding.Security.Mode = BasicHttpsSecurityMode.Transport; var integerMaxValue = int.MaxValue; httpsBinding.MaxBufferSize = integerMaxValue; httpsBinding.MaxReceivedMessageSize = integerMaxValue; httpsBinding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; httpsBinding.AllowCookies = true; httpsBinding.ReceiveTimeout = timeout; httpsBinding.SendTimeout = timeout; httpsBinding.OpenTimeout = timeout; httpsBinding.CloseTimeout = timeout; return httpsBinding; }
创建客户端的代码:
_RedemptionServiceClient = new RedemptionLiteIntegrationServiceClient("https://78.93.37.230:9799/RedemptionLiteIntegrationServiceBasicHttpEndPoint", new TimeSpan(1, 30, 0),"","");
修复方案
强制客户端使用自定义绑定
你当前使用的客户端构造方法未传入自定义绑定,导致程序依然加载默认的CustomBinding(缺失Transport元素)。修改客户端初始化逻辑,明确传入你定义的BasicHttpsBinding实例:var customBinding = GetBindingForEndpoint(new TimeSpan(1, 30, 0)); var endpointAddr = new EndpointAddress("https://78.93.37.230:9799/RedemptionLiteIntegrationServiceBasicHttpEndPoint"); _RedemptionServiceClient = new RedemptionLiteIntegrationServiceClient(customBinding, endpointAddr); // 单独设置凭证(如果需要) _RedemptionServiceClient.ClientCredentials.UserName.UserName = ""; _RedemptionServiceClient.ClientCredentials.UserName.Password = "";使用绑定+端点地址的构造重载,能绕过默认配置加载逻辑,强制使用你定义的合法绑定。
确认服务端绑定兼容性
检查服务端是否使用BasicHttpBinding(HTTPS版本),如果服务端是其他绑定类型(如WsHttpBinding),需同步调整客户端绑定类型,避免因绑定不兼容触发元素缺失错误。若需手动构建CustomBinding(不推荐)
如果必须使用CustomBinding,需手动添加Transport元素,示例代码:var customBinding = new CustomBinding(); // 添加消息编码器元素 customBinding.Elements.Add(new TextMessageEncodingBindingElement()); // 必须添加HTTPS传输元素 customBinding.Elements.Add(new HttpsTransportBindingElement { ClientCredentialType = HttpClientCredentialType.Basic });
内容的提问来源于stack exchange,提问作者Mariana Nagy
相关产品推荐
相关产品推荐

