我想覆盖存储在 app.config 中的客户端 WCF 端点地址,以便我可以将它们从指向“本地主机”更改为指向生产 URL [取决于可以从应用程序中设置的配置(包含在一个对象中)如下所示代码中的“appConfig”)- 这是一个 WinForms 项目。]
通过阅读该领域的其他问题,我得到了以下从 Form_Load 事件调用的代码片段(调用 InitEndpoint 的 InitAllEndpoints)。我在我的应用程序中尝试了这些,如果我将鼠标悬停在“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 ...
}
关于c# - 我能否以编程方式覆盖客户端 app.config WCF 端点地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10319253/