WCF 客户端配置 : how can I check if endpoint is in config file,,如果不是,则回退到代码?

标签 wcf wcf-client wcf-configuration

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

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

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

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

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

我发现的是:

  • new Client();如果未找到配置文件定义,则失败。
  • new Client(binding,endpoint);作品

  • 所以:
    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”对象将公开一个名为“endpoints”的集合,允许您访问在配置文件中找到的所有属性。

    确保您也将“if”的“else”分支视为失败案例(配置无效)。

    关于WCF 客户端配置 : how can I check if endpoint is in config file,,如果不是,则回退到代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1009757/

    相关文章:

    .net-4.0 - WCF 在客户端和主机之间共享对象

    c# - WCF FaultException<SqlException> 被捕获为 CommunicationException

    c# - WCF 和数据契约 : Decimal giving 4 digits after the "." and sometimes only 2 digits

    .net - 我应该在 IIS 中托管我的 WCF 服务吗?

    wcf - 基于 Basichttpbinding 的自托管 WCF 服务不支持超过 1000 个并发请求

    rest - 即使指定了 WebGet 属性,WCF 代理仍使用 Post(仅当从另一个 WCF 服务调用时)- 导致 405 错误

    c# - 如何在不使用配置文件的情况下以编程方式添加 maxItemsInObjectGraph?

    c# - 如何将 wcf 服务添加到现有类库

    .net - 在服务实现的合约列表中找不到 IMetaDataExchange

    c# - 在区域外的 MVC 应用程序中托管 WCF 服务