WCF Client Configuration: how can I check if endpoint is in config file, and fallback to code if not?

半城伤御伤魂 提交于 2019-12-02 23:37:38

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
    }
}

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

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

klashar

I would like to propose improved version of AlexDrenea solution, that uses only special types for configuration sections.

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

        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!