WCF客户端配置:如何检查端点是否在配置文件中,如果没有则回退到代码?

StackOverflow https://stackoverflow.com/questions/1009757

希望使客户端通过WCF将序列化的Message对象发送回服务器。

为了让最终开发人员(不同部门)更容易,他们不需要知道如何编辑他们的配置文件来设置客户端点数据。

也就是说,端点没有嵌入/硬编码到客户端也很棒。

在我看来,混合方案是推出最简单的解决方案:

IF(在config中描述)USE配置文件ELSE回退到硬编码端点。

我发现的是:

  1. new Client(); 如果找不到配置文件定义则会失败。
  2. new Client(绑定,端点); 工作
  3. 因此:

    Client client;
    try {
      client = new Client();
    }catch {
      //Guess not defined in config file...
      //fall back to hard coded solution:
      client(binding, endpoint)
    }
    

    但有没有办法检查(除了try / catch)以查看配置文件是否有声明的端点?

    如果在配置文件中定义,但上面的配置是否也会失败,但配置不正确?区分这两个条件会不错?

有帮助吗?

解决方案

这是读取配置文件并将数据加载到易于管理的对象中的方法:

Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup csg = c.GetSectionGroup("system.serviceModel");
if (csg != null)
{
    ConfigurationSection css = csg.Sections["client"];
    if (css != null && css is ClientSection)
    {
        ClientSection cs = (ClientSection)csg.Sections["client"];
        //make all your tests about the correcteness of the endpoints here
    }
}

“cs” object将公开名为“endpoints”的集合。这允许您访问在配置文件中找到的所有属性。

请务必同时处理“其他”字样。 “if”的分支并将它们视为失败案例(配置无效)。

其他提示

我想提出改进版的 AlexDrenea 解决方案,该解决方案仅对配置部分使用特殊类型。

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup serviceModelGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);
        if (serviceModelGroup != null)
        {
            ClientSection clientSection = serviceModelGroup.Client;
            //make all your tests about the correcteness of the endpoints here

        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top