我可以以编程方式覆盖客户端app.config WCF端点地址吗?

Pau*_*l H 1 c# wcf web-services winforms

我想覆盖存储在app.config中的客户端WCF端点地址,以便我可以将它们从指向"localhost"更改为指向生产URL [取决于可以在App中设置的配置(包含在对象'appConfig'中)在下面显示的代码中) - 这是一个WinForms项目.

通过阅读该领域的其他问题,我已经达到了以下代码片段(InitAllEndpoints调用InitEndpoint),我从Form_Load事件中调用了这些代码.我在我的应用程序中尝试了这些,如果我将鼠标悬停在"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);
}
Run Code Online (Sandbox Code Playgroud)

注意:我的代理服务器位于一个单独的项目/ DLL中.

例如

public class JournalProxy : ClientBase<IJournal>, IJournal
{
    public string StoreJournal(JournalInformation journalToStore)
    {
        return Channel.StoreJournal(journalToStore);
    }


}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ike 5

我这样做的唯一方法是替换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 ...
}
Run Code Online (Sandbox Code Playgroud)