【问题标题】:Consuming web service with c# and basic authentication [duplicate]使用 C# 和基本身份验证使用 Web 服务 [重复]
【发布时间】:2016-09-06 17:19:34
【问题描述】:

我想使用此代码使用 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 服务”的问题重复。 Bushwacka 面临的问题是服务器配置为使用抢先式身份验证。一个非常特殊的情况,它要求客户端在 SOAP 标头中发送身份验证信息。前面提到的问题都没有解决这些问题。

标签: c# web-services wcf basic-authentication


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答,但我无法访问主机,我只能使用该服务。我测试了通过 SoapUI 工具发送请求,它工作正常,在那里我发送了带有用户名和密码的请求,并使用了抢先身份验证,所以我需要在 C# 中进行操作
  • 完美,现在运行良好!
  • 上帝保佑你!
  • 上帝再次保佑你!
  • 上帝也祝福你!
猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多