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

我尝试将应用程序(客户机)连接到公开的 WCF 服务,但不是通过应用程序配置文件,而是通过代码。

我该怎么做呢?

132438 次浏览

您必须使用 频道工厂类。

这里有一个例子:

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

相关资源:

您还可以执行“ ServiceReference”生成的代码所执行的操作

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