在ChannelFactory上更改URL
本文关键字:URL ChannelFactory | 更新日期: 2023-09-27 18:17:19
当我使用WCF将客户端连接到服务时,我使用channelfactory:
new ChannelFactory<T>(endpointConfigurationName);
这将从配置文件中加载所有设置,在这种情况下是很多的。现在我需要在使用通道之前更改URL,该怎么做?我在ChannelFactory上找不到任何URL ?我可以在创建通道时提供EndpointAddress,但我怀疑这会从配置文件中重置我的设置?
我使用channelfactory是为了避免每次更改都生成一个新的代理,并能够设置凭据。
编辑:这就是我解决它的方法
for(int i = 0; i < clientSection.Endpoints.Count; i++)
{
if(clientSection.Endpoints[i].Name == endpointConfigurationName)
{
var endpointAddress = new EndpointAddress(clientSection.Endpoints[i].Address.ToString());
var netHttpBinding = new NetHttpBinding(clientSection.Endpoints[i].BindingConfiguration);
var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), netHttpBinding, endpointAddress);
var channelFactory = new ChannelFactory<T>(serviceEndpoint);
break;
}
}
您可以使用通用包装器方法:
public TProxy CreateChannel(string newEndpointAddress)
{
_endpointAddress = newEndpointAddress;
var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(newEndpointAddress));
return factory.CreateChannel();
}
我们的处境一样。使用多个绑定配置。看到:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="DcServiceBasicBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:801/Service.svc" binding="basicHttpBinding" bindingConfiguration="DcServiceBasicBinding"
contract="Service.IService" name="basicHttpDcServer"/>
<endpoint address="http://10.0.0.1:801/Service.svc" binding="basicHttpBinding" bindingConfiguration="DcServiceBasicBinding"
contract="Service.IService" name="VpnEndpoint"/>
</client>
</system.serviceModel>
然后,从你的代码中,像这样调用:
public void Init(string endpoint = Config.SERVICE_ENDPOINT) {
_service = new ServiceClient(endpoint);
}
其中endpoint为配置
中的端点名称注:删除了一些出于个人目的的名字