如何用特定的Url地址初始化wcf客户端?

问题描述:

我记得ASMX有一个简单的解决方案:如何用特定的Url地址初始化wcf客户端?

MyAsmxServiceClient serviceClient = 
    new MyAsmxServiceClient("http://myServiceLocation/myService.asmx"); 

如何能实现与WCF一样吗?

这通常在App.config/web.config中完成的:

<system.serviceModel> 
    <client> 
     <endpoint 
      address="http://myServiceLocation/myService.asmx" 
      binding="basicHttpBinding" 
      contract="IMyServiceContract" /> 
    </client> 
</system.serviceModel> 

,或者你could also do it programatically如果你喜欢。

通常,当您使用svcutil.exe生成客户端代理时,它也会创建一个示例文件output.config,其中包含设置配置所需的全部内容。


UPDATE:

你也可以提供一个名字,你的终点:

<system.serviceModel> 
    <client> 
     <endpoint 
      name="foo" 
      address="http://foo.com/myService.asmx" 
      binding="basicHttpBinding" 
      contract="IMyServiceContract" /> 
     <endpoint 
      name="bar" 
      address="http://bar.com/myService.asmx" 
      binding="basicHttpBinding" 
      contract="IMyServiceContract" /> 
    </client> 
</system.serviceModel> 

然后:

using (var client = new MyClientProxy("foo")) 
{ 
    var result = client.SomeMethod(); 
} 
+0

这个看起来不错,那么有没有办法为相同的合同定义2个端点并通过名称或其他东西来检索它们? – dexter 2011-03-02 22:16:58

+1

@乍得谁爱我,是的,你可以。我已经更新了我的答案以包含一个例子。 – 2011-03-02 22:19:41

+0

谢谢!奇迹般有效! – dexter 2011-03-02 22:31:27

在同样的思路,结合=结合型使用的是

BasicHttpBinding binding = new BasicHttpBinding(); 
EndpointAddress address = new EndpointAddress("http://localhost:8888/MyService");   
MyServiceClient sv= new MyServiceClient(binding, address) 
+0

如何初始化绑定对象? – dexter 2011-03-02 22:15:45

+0

以上更新假定您使用BasicHttpBinding。希望能帮助到你。 – Kumar 2011-03-02 22:18:47

+0

没有,不幸的是,这个例外是与客户端处于故障状态的事情。 – dexter 2011-03-02 22:32:21