Sometimes, in a production environment, we need this kind of hosting due to some security reasons. To host a service through a program, we have to follow certain rules which make the process very easy.
I am not going to explain over here how to create certificates and import certificates. If you want to learn it, then refer to my earlier article.
Now, we are directly jumping to the problem statement.
I am going to use these two certificates.
- Service Certificate
- Client Certificate
Note
Don't keep any service bindings in app.config.
Don't keep any service bindings in app.config.
Service Side Code
- ServiceHost svcHost = new ServiceHost(typeof(SampleWCFServiceLibrary.Service1));
- NetTcpBinding binding = new NetTcpBinding();
- binding.Security.Mode = SecurityMode.Message;
- binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
- svcHost.AddServiceEndpoint(typeof(SampleWCFServiceLibrary.IService1), binding, "net.tcp://127.0.0.1:8798/Service1");
- svcHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ServiceCert");
- svcHost.Credentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "ClientCert");
- svcHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
- svcHost.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine;
- svcHost.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
- svcHost.Credentials.ClientCertificate.Authentication.MapClientCertificateToWindowsAccount = false;
- svcHost.Open();
- Console.WriteLine("Service Hosted Sucessfully");
Sourav Kumar DasPosted Sep 30, 2019, 11:32 PM
Very Useful Article.