當你在visual studio裡 用 add service reference 調用一個只需X.509 certificate 簽名 https WCF Service ,visual studio 自動生成一些代碼和app.config或者web.config xml代碼,基於這些自動生成的東東,很容易調用,但是部署時比較麻煩,得拷貝那些xml代碼。
我搞了很長時間,終於搞懂了手工實現或者 programmatically implement,也就是無需機器生成的config xml代碼
主要是給ChannelFactory添加X.509 certificate
service url 是 https://service.uhone.com/QuoteTransfer/QuoteTransfer.svc
[csharp]
BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.Certificate;
EndpointAddress endpoint = new EndpointAddress(url);
ChannelFactory<QuoteTransferContract> factory = new ChannelFactory<QuoteTransferContract>(binding, endpoint);
factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=****");
QuoteTransferContract proxy = factory.CreateChannel();
return proxy.SaveQuoteTransfer(request);