希望制作一个通过 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/