Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically connect a client to a WCF service?

I'm trying to connect an application (the client) to an exposed WCF service, but not through the application configuration file, but in code.

How should I go about doing this?

like image 770
Alex Avatar asked May 31 '10 11:05

Alex


People also ask

How do I connect to WCF?

With the service running, right click the project that will contain the WCF client proxy and select Add > Service Reference. In the Add Service Reference Dialog, type in the URL to the service you want to call and click the Go button. The dialog will display a list of services available at the address you specify.

How can I call WCF service using postman?

If you want to call a remote WCF service from Postman (that you can't run locally), debug your local project, so the WCF Test Client opens. 1.) Right-click on the 'My Service Projects' tree node in WCF Test Client, and click 'Add Service'.


2 Answers

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding(); var myEndpoint = new EndpointAddress("http://localhost/myservice"); using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint)) {     IMyService client = null;      try     {         client = myChannelFactory.CreateChannel();         client.MyServiceOperation();         ((ICommunicationObject)client).Close();         myChannelFactory.Close();     }     catch     {         (client as ICommunicationObject)?.Abort();     } } 

Related resources:

  • How to: Use the ChannelFactory
like image 83
Enrico Campidoglio Avatar answered Sep 25 '22 15:09

Enrico Campidoglio


You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX {     public ServiceXClient() { }      public ServiceXClient(string endpointConfigurationName) :         base(endpointConfigurationName) { }      public ServiceXClient(string endpointConfigurationName, string remoteAddress) :         base(endpointConfigurationName, remoteAddress) { }      public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :         base(endpointConfigurationName, remoteAddress) { }      public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :         base(binding, remoteAddress) { }      public bool ServiceXWork(string data, string otherParam)     {         return base.Channel.ServiceXWork(data, otherParam);     } } 

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911")); client.ServiceXWork("data param", "otherParam param"); 
like image 39
joseph.l.hunsaker Avatar answered Sep 25 '22 15:09

joseph.l.hunsaker