具有登录密码身份验证的WCF客户端

时间:2014-03-13 09:32:31

标签: c# web-services wcf

我尝试连接到异地asmx-service。我有asmx url和login-password进行身份验证。我已经为服务添加了服务引用,VS 2010生成了带有config的WCF客户端:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="serviceSoap" />
        </basicHttpBinding>
        <customBinding>
            <binding name="serviceSoap12">
                <textMessageEncoding messageVersion="Soap12" />
                <httpTransport />
            </binding>
        </customBinding>
    </bindings>
    <client>
        <endpoint address="http://tourml.danko.ru:9191/Service.asmx"
            binding="basicHttpBinding" bindingConfiguration="serviceSoap"
            contract="DankoTourMLService.serviceSoap" name="serviceSoap" />
        <endpoint address="http://tourml.danko.ru:9191/Service.asmx"
            binding="customBinding" bindingConfiguration="serviceSoap12"
            contract="DankoTourMLService.serviceSoap" name="serviceSoap12" />
    </client>

我已经使用basicHttpBinding创建了客户端并设置了凭据。然后我试着打电话给服务方法:

var service = new serviceSoapClient("serviceSoap");

service.ClientCredentials.UserName.UserName = username;
service.ClientCredentials.UserName.Password = password;            

var items = service.GetItemList();

但是这里抛出了System.ServiceModel.Security.MessageSecurityException:

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was ''.

内部System.Net.WebException:

{"The remote server returned an error: (401) Unauthorized."}

ClientCredentials设置有什么问题?我应该使用另一个绑定,而不是basicHttpBinding吗?

2 个答案:

答案 0 :(得分:0)

http://msdn.microsoft.com/en-us/library/ms732391(v=vs.110).aspx 根据以上所述。当您需要指定凭据时,端点应具有安全性集。在您的配置中不是这种情况。

两种可能性=&gt; addservice引用无法创建正确的配置(不太可能)。 second =&gt;您必须在服务上而不是在传输上指定凭据。

var service = new serviceSoapClient("serviceSoap");

//service.ClientCredentials.UserName.UserName = username;
//service.ClientCredentials.UserName.Password = password;            

service.setCredentials() (or something)
var itmes = service.getItems();

您应该查找该服务的文档。

答案 1 :(得分:0)

我知道这是一个老帖子,但最近我有同样的问题,也许会帮助别人我是如何解决它的。我有一个.net网络应用程序,为支付系统使用SOAP服务,具有基本身份验证。解决方案是使用客户端凭证在用户名前面加上“u”,并在web.config中指定绑定传输。

client.ClientCredentials.UserName.UserName = "uMyUsername";
client.ClientCredentials.UserName.Password = "MyPassword";

在web.config中:

<bindings>
  <basicHttpBinding>
    <binding name="XYZ">
      <security mode="Transport" >
        <transport clientCredentialType="Basic"/>
      </security>
    </binding>
    <binding name="XYZ" />
  </basicHttpBinding>
</bindings>