This question already has answers here:
How to pass user credentials to web service?
(2个答案)
4年前关闭。
我想使用以下代码使用Web服务:
我的配置如下所示:
该请求被发送到Web服务,并以不正确的消息发送回响应,该消息表明它需要基本身份验证,因为该请求可能是没有凭据发送的,所以我不知道错误在哪里。
感谢您的帮助
(2个答案)
4年前关闭。
我想使用以下代码使用Web服务:
WebService.GenRelClient client = new WebService.GenRelClient();
client.ClientCredentials.UserName.UserName = @"UserName";
client.ClientCredentials.UserName.Password = @"Password";
var response = client.returnString("test");
我的配置如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="GenRelClientPortBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint
address="http://ws.domain.com/GenRel/GenRel"
binding="basicHttpBinding"
bindingConfiguration="GenRelClientPortBinding"
contract="WebService.GenRelClientPort"
name="GenRelClientPort" />
</client>
</system.serviceModel>
</configuration>
该请求被发送到Web服务,并以不正确的消息发送回响应,该消息表明它需要基本身份验证,因为该请求可能是没有凭据发送的,所以我不知道错误在哪里。
感谢您的帮助
最佳答案
为了能够调用Web服务,您将需要在SOAP header 中添加安全信息。
单击here以阅读MSDN文章,其中解释了基本原理。
查看下面的代码示例,看看它是否可以解决您的问题:
var client = new WCClient();
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));
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.DoSomething();
}