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?
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.
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'.
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:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With