如何为SOAP客户端切换不同终结点?可行性及实现方法
问题
现有一段使用SOAP客户端的代码:
using (webTest.TestSoapClient sc = new webPrint.TestSoapClient()) { sc.Print(); }
web.config中配置了如下终结点:
<client> <endpoint address="http://localhost/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap" /> </client>
现在想在web.config中添加更多终结点,示例如下:
<endpoint address="http://example.com/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap1" /> <endpoint address="http://123.com/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap2" /> </client>
请问能否通过如下代码指定不同终结点名称创建SOAP客户端:
using (webTest.TestSoapClient sc = new webPrint.TestSoapClient("TestSoap1")) { sc.Print(); } using (webTest.TestSoapClient sc = new webPrint.TestSoapClient("TestSoap2")) { sc.Print(); } using (webTest.TestSoapClient sc = new webPrint.TestSoapClient("TestSoap3")) { sc.Print(); }
该方案是否可行?具体该如何实现?
答案
这个方案完全可行,具体实现步骤和注意事项如下:
1. 补全Web.config的客户端配置
确保所有新增终结点都正确嵌套在<client>节点内,完整配置示例:
<client> <endpoint address="http://localhost/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap" /> <endpoint address="http://example.com/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap1" /> <endpoint address="http://123.com/webservice/test.asmx" binding="basicHttpBinding" bindingConfiguration="TestSoap" contract="webTest.TestSoap" name="TestSoap2" /> </client>
2. 按终结点名称实例化客户端
你提供的代码逻辑是正确的:TestSoapClient的构造函数支持传入终结点名称,WCF框架会自动匹配Web.config中对应name属性的终结点配置,从而连接到指定地址的Web服务。
3. 关键注意事项
- 代码中
TestSoap3的实例化会直接报错,因为Web.config中未定义该名称的终结点,运行时会抛出EndpointNotFoundException,必须保证构造函数传入的名称和配置文件中的name完全一致。 - 所有终结点的
contract属性必须与客户端代理的契约(webTest.TestSoap)一致,否则无法完成匹配。 - 若不同终结点需要不同的绑定规则,需对应配置独立的
<binding>节点;你当前所有终结点共用TestSoap绑定配置,只要该配置本身有效即可正常使用。
内容的提问来源于stack exchange,提问作者want_to_be_calm
相关产品推荐
相关产品推荐

