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

And*_*rei 73 c# wcf wcf-binding wcf-client

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

我应该怎么做呢?

Enr*_*lio 110

您必须使用ChannelFactory类.

这是一个例子:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

相关资源:

  • 十分感谢.另外,以下是如何在应用程序中使用IMyService对象:http://msdn.microsoft.com/en-us/library/ms733133.aspx (4认同)
  • 我将此与[此答案](http://stackoverflow.com/a/573925/345659)相结合,效果很好.谢谢 (2认同)

jos*_*ker 6

您还可以执行"服务引用"生成的代码所执行的操作

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

IServiceX是您的WCF服务合同

那你的客户代码:

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