【发布时间】:2011-02-25 22:54:23
【问题描述】:
我正在尝试将应用程序(客户端)连接到公开的 WCF 服务,但不是通过应用程序配置文件,而是通过代码。
我该怎么做呢?
【问题讨论】:
-
对于任何搜索这个的人,看看这个答案:stackoverflow.com/a/839941/592732
标签: c# wcf wcf-binding wcf-client
我正在尝试将应用程序(客户端)连接到公开的 WCF 服务,但不是通过应用程序配置文件,而是通过代码。
我该怎么做呢?
【问题讨论】:
标签: c# wcf wcf-binding wcf-client
您必须使用 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();
}
}
相关资源:
【讨论】:
client 转换为IClientClient 才能关闭它。
IMyService 接口继承自System.ServiceModel.ICommunicationObject。我修改了示例代码以使其更清晰。
你也可以做“服务参考”生成的代码做的事情
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");
【讨论】: