![](/img/trans.png)
[英]How to programmatically modify WCF app.config endpoint address setting?
[英]Can I programmatically override client app.config WCF endpoint addresses?
我想覆盖存储在app.config中的客户端WCF终结点地址,以便可以将它们从指向“本地主机”更改为指向生产URL [取决于可以在App内部设置的配置(包含在对象'appConfig'中)在下面显示的代码中)-这是一个WinForms项目。]
通过阅读该领域的其他问题,我到达了以下代码(从InitEndpoints调用InitEndpoint),这些代码是我从Form_Load事件调用的。 我在应用程序中尝试了这些,如果将鼠标悬停在“ ep”变量中的值上,它们似乎会更改端点地址。 但是,如果我在代码之后再次通过serviceModelSectionGroup.Client.Endpoints循环,我发现它们实际上并没有改变。 (我现在读到EndPoint地址是不可变的-所以我的代码看起来还是错误的,因为我希望用新的EndPoint地址对象而不是Uri覆盖该地址?)
如何以编程方式覆盖客户端app.config WCF端点地址?
private void InitAllEndpoints()
{
ServiceModelSectionGroup serviceModelSectionGroup =
ServiceModelSectionGroup.GetSectionGroup(
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None));
if (serviceModelSectionGroup != null)
{
foreach (ChannelEndpointElement ep in serviceModelSectionGroup.Client.Endpoints)
{
InitEndpoint(ep,
appConfig.ExternalComms_scheme,
appConfig.ExternalComms_host,
appConfig.ExternalComms_port);
}
}
}
private void InitEndpoint(ChannelEndpointElement endPoint, string scheme, String host, String port)
{
string portPartOfUri = String.Empty;
if (!String.IsNullOrWhiteSpace(port))
{
portPartOfUri = ":" + port;
}
string wcfBaseUri = string.Format("{0}://{1}{2}", scheme, host, portPartOfUri);
endPoint.Address = new Uri(wcfBaseUri + endPoint.Address.LocalPath);
}
注意:我的代理位于单独的项目/ DLL中。
例如
public class JournalProxy : ClientBase<IJournal>, IJournal
{
public string StoreJournal(JournalInformation journalToStore)
{
return Channel.StoreJournal(journalToStore);
}
}
我这样做的唯一方法是在每个客户端的构造实例上替换EndpointAddress
。
using (var client = new JournalProxy())
{
var serverUri = new Uri("http://wherever/");
client.Endpoint.Address = new EndpointAddress(serverUri,
client.Endpoint.Address.Identity,
client.Endpoint.Address.Headers);
// ... use client as usual ...
}
我通过在客户端代理中使用ClientBase <>构造函数来修改客户端上wcf服务的端点
public class JournalProxy : ClientBase<IJournal>, IJournal
{
public JournalProxy()
: base(binding, endpointAddress)
{
}
public string StoreJournal(JournalInformation journalToStore)
{
return Channel.StoreJournal(journalToStore);
}
}
在我的情况下,我从客户端代理中的数据库设置创建绑定和端点,您也许可以使用ClientBase(string endpointConfigurationName,string remoteAddress)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.