Search code examples
c#.netwebservice-clientservice-model

How can I dynamically set a .Net 3.5 Web Service that uses SSL?


I'm writing an application that needs to connect to a web service. Under certain circumstances, I need to toggle the endpoint address.

I assume this is as simple as changing the System.ServiceModel.Description.ServiceEndpoint, when the address needs to change. However, I'm getting an exception when I do this because one addresses requires SSL, and the other address doesn't.

How can I correctly update web services endpoint address?

Note: This is a C#, .Net 3.5 project.


Solution

  • Ok, I found the solution. When Visual Studio generates the wrapper classes for your service, the [ServiceName]SoapClient has a constructor that takes a binding and an endpoint as a parameter. Define these and just pass them to the constructor.

    Here is a pseudo-example.

        void InitializeMyWebService(bool useSSLSite)
        {
            BasicHttpBinding b = useSSLSite ? 
                new BasicHttpBinding(BasicHttpSecurityMode.Transport) : 
                new BasicHttpBinding();
    
            EndpointAddress e = useSSLSite ? 
                new EndpointAddress("https://www.example.com/svc/MyWebService.asmx") :
                new EndpointAddress("http://intranet_server/svc/MyWebService.asmx");
    
            myWebService = new MyWebServiceSoapClient(b, e);
        }
    }
    

    MyWebService will now work, as defined by the userSSLSite parameter to our method.