带WS安全的WebService调用异常:C#代码配置求助
解决WS安全WebService的C#调用异常问题
问题根源分析
- 初始配置中手动硬编码wsse头与代码中
ClientCredentials设置冲突,导致认证失败;同时security mode="Transport"下,message节点的配置不会生效,无法正确传入WS-Security的用户名凭证。 - 切换到
TransportWithMessageCredential时,错误提示的契约名称不匹配,是因为实例化客户端时未指定正确端点名称,或是配置中的契约命名空间与代码生成的不一致。
修正步骤及代码示例
1. 修正app.config配置
移除手动添加的<headers>节点,调整binding的security配置,确保端点契约与代码生成的完全一致:
<system.serviceModel> <client> <endpoint address="https://*************/DocumentUploadWS" <!-- 注意:去掉.wsdl后缀,使用实际服务地址 --> binding="basicHttpBinding" bindingConfiguration="DocumentUploadWSSoap11" contract="DocumentWSWs.DocumentUploadWS" name="DocumentEndPoint" /> </client> <bindings> <basicHttpBinding> <binding name="DocumentUploadWSSoap11"> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> </bindings> </system.serviceModel>
security mode="TransportWithMessageCredential":对应HTTPS传输层安全 + SOAP消息层的WS-Security用户名认证,和SOAP UI测试的场景匹配
2. 修正C#调用代码
实例化客户端时指定端点名称(避免契约匹配问题),确保TLS版本符合服务端要求:
// 启用服务端支持的TLS版本,比如TLS1.2 private void SetTlsSecurite() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; } // 调用逻辑 using (var client = new DocumentWSWs.DocumentUploadWSClient("DocumentEndPoint")) // 指定端点名称 { client.ClientCredentials.UserName.UserName = UserNameWs; client.ClientCredentials.UserName.Password = PasswordWs; SetTlsSecurite(); DocumentWSWs.StatusRequest currentStatusRequest = new DocumentWSWs.StatusRequest(); DocumentWSWs.StatusResponse getCurrentStatusResponse = client.GetStatus(currentStatusRequest); }
额外注意事项
- 确认代码生成的WebService客户端契约命名空间
DocumentWSWs与配置中contract属性完全一致,大小写也不能出错 - 如果服务端要求密码为Digest类型,可在
<message>节点添加passwordType="Digest",但你的SOAP UI测试用的是PasswordText,保持当前设置即可 - 排查服务端是否限制客户端IP访问,避免防火墙或权限拦截
内容的提问来源于stack exchange,提问作者Akrem
相关产品推荐
相关产品推荐

