使用 NTLM 身份验证的 SOAP Web 服务调用无法正常工作 C#

SOAP web service call with NTLM auth not working C#

我正在尝试使用 NTLM 身份验证进行 SOAP 网络服务调用,但它不起作用。

我使用了 WSDL 服务。

到目前为止我做了什么:

BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://uri.test/");
_client = new TEST_PortClient(binding, address);

if (_client.ClientCredentials != null)
{
  _client.ClientCredentials.Windows.AllowNtlm = true; // this method is deprecated
  _client.ClientCredentials.Windows.ClientCredential.UserName = "username";
  _client.ClientCredentials.Windows.ClientCredential.Password = "password";
}
_client.Open(); // this works successfully
string message = string.Empty;
if (_client.TestConnection(ref message)) // this throw an exception *
{
  // do something
}

抛出的异常是:

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'.

我应该怎么做才能让它发挥作用?

我是这样解决的:

BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress(Uri);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = Encoding.UTF8;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;

_client = new TEST_PortClient(binding, address);

if (_client.ClientCredentials != null)
{
  _client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("username", "password");
  _client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;

}
_client.Open();

string message = string.Empty;
if (_client.TestConnection(ref message))
{
  // do something
}