【问题标题】:How to programmatically connect a client to a WCF service?如何以编程方式将客户端连接到 WCF 服务?
【发布时间】:2011-02-25 22:54:23
【问题描述】:

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

我该怎么做呢?

【问题讨论】:

标签: c# wcf wcf-binding wcf-client


【解决方案1】:

您必须使用 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();
    }
}

相关资源:

【讨论】:

  • 太好了,谢谢。另外,以下是如何让 IMyService 对象在您的应用程序中使用:msdn.microsoft.com/en-us/library/ms733133.aspx
  • 您应该将client 转换为IClientClient 才能关闭它。
  • 在我的示例中,我假设IMyService 接口继承自System.ServiceModel.ICommunicationObject。我修改了示例代码以使其更清晰。
  • @EnricoCampidoglio 问题:您是否必须在每次要拨打电话时重新创建频道,或者您可以将 IService 存储在全局变量中以便在整个过程中重复使用?当我使用此方法测试我的连接时,它可以工作,但后来如果我尝试在单独的方法中执行调用,我会收到“无端点监听”错误?
  • 我将它与this answer 结合使用,效果很好。谢谢
【解决方案2】:

你也可以做“服务参考”生成的代码做的事情

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2015-02-15
    • 1970-01-01
    • 2011-01-11
    • 2019-10-27
    • 2013-02-22
    相关资源
    最近更新 更多