Search code examples
c#asp.net.netwcf

Change WebService Endpoint from HTTP to HTTPS


I'm really new to .NET and I have come to a roadblock (I guess).

I have a project that needs changing one address for another service we use, this address changed from HTTP to HTTPS.

My question is, for this change, do I need to change the code of the method that invokes the request, so I load the certificate in there, or do I just change the endpoint config?

I've tried the endpoint config security binding from None to TransportWithMessageCredential, also loading the certificate to the machine repository, but I'm not sure how do I specify what certificate I want to send.


Solution

  • I guess you are using BasicHttpBinding right now, and need to change from a HTTP endpoint to a HTTPS endpoint that requires validation through X509 certificate. I'm assuming you're using C#.

    If you're using any version of .NET Framework older than 4.5, you can do:

    var binding = new BasicHttpBinding(BasicHttpsSecurityMode.Transport);
    

    If you are using .NET Framework 4.5 or newer version, you can do like this:

    var binding = new BasicHttpsBinding();
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
    

    Assuming you've imported the WebService definition deriving from System.ServiceModel.ClientBase (like when you right-click the project in Visual Studio and choose Add > Service Reference), you can do something like this:

    var address = new EndpointAddress(serviceUrl);
    var wsClient = new ServiceReference1.YourServiceClient(binding, address);
    // x509Cert is a variable of type 'X509Certificate2'.
    wsClient.ClientCredentials.ClientCertificate.Certificate = x509Cert;
    
    // Take a look at: https://stackoverflow.com/a/49303859/
    wsClient.Open();
    wsClient.CallTheService();
    wsClient.Close();