使用 SOAP Web 服务时如何在 C# 中设置密码类型

How to set Password Type in C# while consuming a SOAP web service

我正在尝试在我的 C# 控制台应用程序中使用第三方 SOAP Web 服务。我尝试了两种不同的方式来传递凭证,如下所示。

//Method 1 - passing security credentials
myCardService.Credentials = new System.Net.NetworkCredential("username", 
"password");

//Method 2 - passing security credentials
System.Net.CredentialCache myCredentials = new System.Net.CredentialCache();
NetworkCredential netCred = new NetworkCredential("username", "password");
myCredentials.Add(new Uri(myCardService.Url), "Basic", netCred);
myCardService.Credentials = myCredentials;

在这两种情况下,我都遇到了这个异常:

System.Web.Services.Protocols.SoapHeaderExceptions: Error in SecurityHeader: An Invalid security token was provided

当我尝试使用 SOAP UI 来使用该服务时,我也遇到了同样的错误。但是,当我在工具的属性 window 中设置 WSS-Password Type = PasswordText 时,它就起作用了。我看不到任何方法可以在 C# 代码的凭据对象中进行此设置。非常感谢任何帮助。

我的理解是,在您定义服务绑定到身份验证类型之后。

binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

定义身份验证类型后,您将创建 Web 服务客户端并执行以下操作:

client.ClientCredentials.Username.Username = networkCredential.Username;
client.ClientCredentials.Password.Password = networkCredential.Password;

这应该是传递这些凭据的适当方式。

我从 https://www.microsoft.com/en-us/download/details.aspx?id=14089 安装 WSE 3.0 并在 Reference.cs 中手动将 Web 引用从 System.Web.Services.Protocols.SoapHttpClientProtocol 更改为 Microsoft.Web。Services3.WebServicesClientProtocol ] 文件。