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

Consuming web service with c# and basic authentication

我想使用此代码使用 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-service,您需要将安全信息添加到 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();
 }