将app.config中的WCF服务客户端实例重构为代码

时间:2015-03-31 16:01:34

标签: c# wcf

我有一个WCF服务引用,我使用以下客户端app.config:

<system.serviceModel>
    <bindings>
        <wsHttpBinding>
            <binding name="WSHttpBinding_ManagerService">
                <security>
                    <message clientCredentialType="UserName" />
                </security>
            </binding>
        </wsHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://myadress:8080/ManagerService.svc"
            binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ManagerService"
            contract="Service.ManagerService" name="WSHttpBinding_ManagerService">
            <identity>
                <certificate encodedValue="AwAAAAEAAAAUAAAAaJ8gJ+2BbDC//Nw76gp1Rx4Ii1AgAAAAAQAAACQDAAAwggMgMIICDKADAgECAhB4jlXUsVcUkE45Bq9sj6cdMAkGBSsOAwIdBQAwIzEhMB8GA1UEAxMYc2tpbGxjb25vbXkuY2xvdWRhcHAubmV0MB4XDTA2MTIzMTIyMDAwMFoXDTE5MTIzMTIyMDAwMFowIzEhMB8GA1UEAxMYc2tpbkjsahdjhdjsdhsjhdsjhdjhdsjhdFAAOCAQ8AMIIBCgKCAQEAwHjDPi/A7+4PfvYt40eySE2I6FgVO2Ewco8gJO21TUqHpKbinmsaNTO6wFJy+l3adMRB0dcmAvH938BPgdwbqbVaaG4mRCDpnekEserWmz5ii+ET1xhm0atIg6xW3sgnDOA+41Y0vB8m8AXTfHQYunILQjn/6xGM/RffK32vbR9WGJKEd/okOJ2/vV5dm2UsejlANwK2kCMe9wNRbjaKsH6PIqv26KeHAXxa0tSzoHfrn/lr46+54WzEXFHRzub1JbZk+IsdsdlakasjdksjdjdksjddjskdZZ0Oj0iG0GjvEVbmHWpBM/WhHrqIfGdqiMtXjOtwIDAQAsdsdsdsdsdsdsdaZtgIq+y6hm91EfPUToJ1ZUhWR8z/RG+IVZrs0O93FCMk6WU8OhYxubIgcVSTx0FDCakyOmfu1gnYeEZv53kVPZSmY4KUAUZz+MCQf/OXN2OGv9cRmsWg4iDlHjzDQwucO+rWkclvQo=" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>

我现在需要重构实例化以使用空白的app.config:

这是我尝试过的:

var binding = new WSHttpBinding();
binding.Security = new WSHttpSecurity { Mode = SecurityMode.Message };
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;            
var store = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var cers = store.Certificates.Find(X509FindType.FindByThumbprint, "123THUMBPRINTOFCERT", false);
var cer = cers[0];
var identity = new X509CertificateEndpointIdentity(cer);
var endpoint = new EndpointAddress(new Uri("http://myservice:8080/ManagerService.svc"), identity);
var client = new ManagerServiceClient(binding, endpoint);
client.ClientCredentials.UserName.UserName = EMail;
client.ClientCredentials.UserName.Password = Password;
var resultBuilder = new StringBuilder();
var categories = client.Categorize(Text);

这会引发异常:

  

System.ServiceModel.Security.MessageSecurityException:客户端不能   根据中的标识确定服务主体名称   目标地址“http://myservice:8080/ManagerService.svc”表示   SspiNegotiation / Kerberos的目的。目标地址标识   必须是UPN身份(如acmedomain \ alice)或SPN身份(如   主机/鲍勃机器)。

我已经检查过,在商店中找到了正确的证书。我很高兴得到一个关于我在这里失踪的提示,以及我在这里的方式是否正常......?

1 个答案:

答案 0 :(得分:2)

你丢了一行clientCredentialType="UserName"

binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;