WCF 客户端配置:如何检查端点是否在配置文件中,如果没有,如何回退到代码? [英] WCF Client Configuration: how can I check if endpoint is in config file, and fallback to code if not?

查看:22
本文介绍了WCF 客户端配置:如何检查端点是否在配置文件中,如果没有,如何回退到代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Looking to make a Client that sends serialized Message objects back to a server via WCF.

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

To make things easy for the end-developer (different departments) would be best that they didn't need to know how to edit their config file to set up the client end point data.

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

That said, would also be brilliant that the endpoint wasn't embedded/hard-coded into the Client either.

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

A mix scenario would appear to me to be the easiest solution to roll out:

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

IF (described in config) USE config file ELSE fallback to hard-coded endpoint.

我发现的是:

  1. new Client(); 如果未找到配置文件定义,则失败.
  2. new Client(binding,endpoint);有效
  1. new Client(); fails if no config file definition found.
  2. new Client(binding,endpoint); works

因此:

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

但是有什么方法可以检查(除了 try/catch)以查看配置文件是否声明了端点?

But is there any way to check (other than try/catch) to see if config file has an endpoint declared?

如果在配置文件中定义,但配置不正确,上面的内容是否也会失败?区分这两种情况会好吗?

Would the above not fail as well if defined in config file, but not configured right? Would be good to distinguish between the two conditions?

推荐答案

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

here is the way to read the configuration file and load the data into an easy to manage object:

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"的集合,允许您访问在配置文件中找到的所有属性.

The "cs" object will expose a collection named "endpoints" that allows you to access all the properties that you find in the config file.

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

Make sure you also treat the "else" branches of the "if"s and treat them as fail cases (configuration is invalid).

这篇关于WCF 客户端配置:如何检查端点是否在配置文件中,如果没有,如何回退到代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆