案例下载
客户端调用代码 通过代理类
代理生成 参见
X509证书创建
服务端配置代码
服务端自定义证书验证类
namespace WcfServiceLibrary1{ public class MyX509Validator : System.IdentityModel.Selectors.X509CertificateValidator { public override void Validate(X509Certificate2 certificate) { if (!certificate.Thumbprint.Equals("B9DF5B912B8CF8EAB07A7BB9B0D17694522AB0CE", StringComparison.CurrentCultureIgnoreCase)) { throw new SecurityTokenException("Unknown Certificate"); } } }}
客户端调用代码
private void btnTest_Click(object sender, EventArgs e) { //Service1Client client = new Service1Client(); //txtMessage.Text = client.GetDataUsingDataContract(new WcfServiceLibrary1.CompositeType() { StringValue = "sssss" }).StringValue; NetTcpBinding binding2 = new NetTcpBinding(); binding2.Security.Mode = SecurityMode.Transport; binding2.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; binding2.Security.Message = new MessageSecurityOverTcp() { ClientCredentialType = MessageCredentialType.Certificate }; EndpointAddress endpoint = new EndpointAddress(new Uri("net.tcp://localhost:8731/WcfServiceLibrary"), EndpointIdentity.CreateDnsIdentity("TestServer")); ChannelFactoryfactory = new ChannelFactory (binding2, endpoint); factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "TestServer"); IService1 client = factory.CreateChannel(); txtMessage.Text = client.GetDataUsingDataContract(new WcfServiceLibrary1.CompositeType() { StringValue = "sssss" }).StringValue; //B9DF5B912B8CF8EAB07A7BB9B0D17694522AB0CE }