如何以编程方式将客户端连接到WCF服务?

我试图将应用程序(客户端)连接到公开的WCF服务,但不是通过应用程序configuration文件,而是在代码中。

我应该怎么做呢?

你将不得不使用ChannelFactory类。

这是一个例子:

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

相关资源:

  • 如何:使用ChannelFactory

您也可以执行“服务参考”生成的代码

 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); } } 

其中IServiceX是您的WCF服务合同

然后你的客户代码:

 var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911")); client.ServiceXWork("data param", "otherParam param");