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

问题描述:

我想使用以下代码使用Web服务:

I want to consume a web service with this code:

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服务,并以错误消息形式返回该请求,该消息表明该请求需要基本身份验证,因为该请求可能是没有凭据发送的,所以我不知道它在哪里错误.

The request is sent to the web service and the response is sent back with incorrect message about that it need Basic Authentication because the request was sent probably without credentials, so I don't know where is the mistake.

谢谢您的帮助

为能够调用Web服务,您需要在SOAP标头中添加安全性信息.

For you to be able to call the web-service you will need to add security information to the SOAP header.

点击在这里阅读一篇解释了基本原理的MSDN文章.

Click here to read an MSDN article that explains the basic principle.

看看下面的代码示例,看看它是否可以解决您的问题:

Take a look at the code sample below and see if it solves your problem:

 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();
 }