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

C# 如何以编程方式将客户端连接到WCF服务?,c#,wcf,wcf-binding,wcf-client,C#,Wcf,Wcf Binding,Wcf Client,我试图将应用程序(客户端)连接到公开的WCF服务,但不是通过应用程序配置文件,而是通过代码 我该怎么做呢?你必须使用这个类 下面是一个例子: var myBinding = new BasicHttpBinding(); var myEndpoint = new EndpointAddress("http://localhost/myservice"); using (var myChannelFactory = new ChannelFactory<IMyService>(myBi

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

我该怎么做呢?

你必须使用这个类

下面是一个例子:

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();
    }
}
var myBinding=new BasicHttpBinding();
var myEndpoint=新端点地址(“http://localhost/myservice");
使用(var myChannelFactory=newchannelfactory(myBinding,myEndpoint))
{
IMyService client=null;
尝试
{
client=myChannelFactory.CreateChannel();
client.MyServiceOperation();
((ICommunicationObject)client.Close();
myChannelFactory.Close();
}
抓住
{
(客户端作为ICommunicationObject)?.Abort();
}
}
相关资源:

您还可以执行“服务参考”生成的代码所执行的操作

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

太好了,谢谢。另外,这里介绍了如何在应用程序中使用IMyService对象:您应该将
client
强制转换为
IClientClient
,以关闭它。在我的示例中,我假设
IMyService
接口继承自。我修改了示例代码以使其更清晰。@Enricoampidoglio问题:您是否必须在每次通话时重新创建频道,或者是否可以将iSeries设备存储在全局变量中以便在整个过程中重复使用?当我使用这个方法测试我的连接时,它是有效的,但是后来如果我尝试在一个单独的方法中执行一个调用,我会得到一个“无端点侦听”错误?我结合了这个方法,效果很好。感谢搜索此内容的任何人,请查看以下答案:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");