使用C#和基本身份验证消费Web服务

8

我想使用这段代码来调用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服务,响应返回了错误消息,说明需要基本认证(Basic Authentication),可能是因为请求没有包含凭据信息导致的。所以,我不知道出了什么问题。
谢谢您的帮助。

1
我不同意这个问题是与标题为“如何将用户凭据传递给 Web 服务”的问题重复的。Bushwacka 面临的问题是服务器配置为使用预先认证。这是一个非常特殊的情况,要求客户端在 SOAP 标头中发送身份验证信息。之前提到的问题没有涉及到这些内容。 - Captain Sensible
1个回答

37

为了能够调用Web服务,您需要将安全信息添加到SOAP标头中。

点击此处阅读解释基本原理的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();
 }

2
完美,现在它运行良好! - Bushwacka
1
愿上帝保佑你! - Fuat
1
上帝再次保佑你! - Márcio Brener
愿上帝也保佑你! - Carlos Torrecillas
愿上帝保佑你、你的家人和所有未来的后代! - Mudo
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接