ConfigurationSection ConfigurationManager.GetSection()始终返回null

Jon*_*Jon 10 c# configurationmanager configurationsection

我正在尝试学习如何使用ConfigurationSection类.我曾经使用IConfigurationSectionHandler,但发布它已被折旧.因此,作为一个好孩子,我正在尝试"正确"的方式.我的问题是它总是返回null.

我有一个控制台应用程序和DLL.

class Program
{
    static void Main(string[] args)
    {           
        StandardConfigSectionHandler section = StandardConfigSectionHandler.GetConfiguration();

        string value = section.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

app配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <sectionGroup name="ConfigSectionGroup">
      <section name="ConfigSection" type="Controller.StandardConfigSectionHandler, Controller" />
    </sectionGroup>
  </configSections>

  <ConfigSectionGroup>
    <ConfigSection>
      <test value="1" />
    </ConfigSection>
  </ConfigSectionGroup>

</configuration>
Run Code Online (Sandbox Code Playgroud)

DLL中的section处理程序:

namespace Controller
{    
    public class StandardConfigSectionHandler : ConfigurationSection
    {
    private const string ConfigPath = "ConfigSectionGroup/ConfigSection/";

    public static StandardConfigSectionHandler GetConfiguration()
    {
        object section = ConfigurationManager.GetSection(ConfigPath);
        return section as StandardWcfConfigSectionHandler;
    }

    [ConfigurationProperty("value")]
    public string Value
    {
        get { return (string)this["value"]; }
        set { this["value"] = value; }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

什么都值我尝试了"用configPath"它会返回null,或抛出一个错误说"测试"是一个无法识别的元素.我试过的价值观:

  • ConfigSectionGroup
  • ConfigSectionGroup /
  • ConfigSectionGroup/ConfigSection
  • ConfigSectionGroup/ConfigSection /
  • ConfigSectionGroup/ConfigSection /测试
  • ConfigSectionGroup/ConfigSection /测试/

Mar*_*son 10

您的代码存在一些问题.

  1. 你总是null在你的GetConfiguration方法中返回,但我会假设这只是问题,而不是你的实际代码.

  2. 更重要的是,ConfigPath值的格式不正确.你有一个尾部斜杠ConfigSectionGroup/ConfigSection/,删除最后一个斜杠,它将能够找到该部分.

  3. 最重要的是,您在配置系统中声明您的部分的方式将期望您的"值"存储在ConfigSection元素的属性中.像这样

    <ConfigSectionGroup>
      <ConfigSection value="foo" />
    </ConfigSectionGroup>
    
    Run Code Online (Sandbox Code Playgroud)

所以,把它们放在一起:

public class StandardConfigSectionHandler : ConfigurationSection
{
    private const string ConfigPath = "ConfigSectionGroup/ConfigSection";

    public static StandardConfigSectionHandler GetConfiguration()
    {
        return (StandardConfigSectionHandler)ConfigurationManager.GetSection(ConfigPath);
    }

    [ConfigurationProperty("value")]
    public string Value
    {
        get { return (string)this["value"]; }
        set { this["value"] = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

要阅读有关如何配置配置部分的更多信息,请参阅此优秀的MSDN文档:如何:使用ConfigurationSection创建自定义配置部分.它还包含有关如何在(与测试元素)的子元素中存储配置值的信息.