【问题标题】:Connection to WCF service after endpoint change at runtime在运行时更改端点后连接到 WCF 服务
【发布时间】:2014-08-21 23:08:02
【问题描述】:

我正在创建一些身份验证表单,用户必须在其中定义 WCF 服务 IP、用户名和密码。

在创建与服务的连接之前,用户输入的端点 IP 地址会保存到 app.config 文件中。见以下代码:

         Configuration configFile = ConfigurationManager.
                                     OpenExeConfiguration(ConfigurationUserLevel.None);
         ServiceModelSectionGroup serviceSection = ServiceModelSectionGroup.
                                                      GetSectionGroup(configFile);

        ClientSection clientSection = serviceSection.Client;
        Uri uri = clientSection .Endpoints[0].Address;

        UriBuilder builder = new UriBuilder(uri);
        builder.Host = ServerIP;
        clientSection .Endpoints[0].Address = builder.Uri;
        configFile.Save(ConfigurationSaveMode.Modified);

在第一次连接到 WCF 时一切正常,也就是说,如果 IP 正确,它将验证用户,如果不正确 - 将显示相应的消息。

但是,如果在第一次连接后更改了服务的端点 IP 并重新创建了客户端对象,它会尝试使用以前的 IP 地址而不是新的 IP 地址连接到服务。

我尝试将新端点直接设置为这样的服务:

          ServiceClient client = new ServiceClient();
          client.Endpoint.Address = new_uri_address;

但没有成功。

我想知道为什么会发生这种情况以及如何正确地将新端点分配给 WCF 客户端?

【问题讨论】:

    标签: c# web-services wcf wcf-endpoint


    【解决方案1】:

    app.config 在程序首次加载时被读取。除非您终止应用程序并重新启动它,否则您的更改不会生效。 为了克服这个问题,您应该从代码中完全定义和配置您的 wcf 客户端。 至少那是对我有用的方法。 如果需要,我可以提供完整的示例

    【讨论】:

    • 感谢您的回答。 App.config 在应用程序启动后更改,但在此更改后首次连接到 WCF 是可以的。第二次更改后会出现问题。如果唯一的方法是完成 wcf 客户端的重新配置,我会尝试这样做。再次感谢
    【解决方案2】:

    为了能够连接到服务,客户端需要三个信息——地址、绑定和合同。可以尝试通过代码设置这些,看看是否使用了新的ip地址。看看这个解决方案:Dynamically set endpoint address in wcf client (with net tcp binding)

    【讨论】:

      【解决方案3】:

      再次感谢您的回答。我通过定义绑定和端点重新创建了 wcf 客户端,它工作正常。

          Configuration configFile = ConfigurationManager.
                                       OpenExeConfiguration(ConfigurationUserLevel.None);
          ServiceModelSectionGroup serviceSection = ServiceModelSectionGroup.
                                                        GetSectionGroup(configFile);
      
          ClientSection clientSection = serviceSection.Client;
      
          System.ServiceModel.Channels.Binding bind = new BasicHttpBinding(clientSection .Endpoints[0].BindingConfiguration);
          EndpointAddress newEndpoint = new EndpointAddress(clientSection .Endpoints[0].Address);
      
          my_service = new TCCSServiceClient(bind, newEndpoint);
      

      【讨论】:

        猜你喜欢
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多