我想覆盖存储在app.config中的客户端WCF端点地址,以便我可以将它们从指向“localhost”的位置更改为指向生产URL [取决于可以从App中设置的配置(包含在“对象”下面显示的代码中的'appConfig') - 这是一个WinForms项目。]我可以以编程方式覆盖客户端app.config WCF端点地址吗?
通过阅读此区域中的其他问题,我已经达到了从Form_Load事件调用的下列代码段(调用InitEndpoint的InitAllEndpoints)。我在我的应用程序中尝试了这些,如果我将鼠标悬停在“ep”变量的值上,它们似乎会更改EndPoint地址。然而,如果我通过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);
}
}
这可能是你在找什么... http://stackoverflow.com/questions/5151077/wcf-change-endpoint-address-at-runtime – 2012-04-25 16:12:11