[英]ConfigurationSection ConfigurationManager.GetSection() always returns null
我正在嘗試學習如何使用ConfigurationSection類。 我曾經使用IConfigurationSectionHandler,但發布它已被折舊。 因此,作為一個好孩子,我正在嘗試“正確”的方式。 我的問題是它總是返回null。
我有一個控制台應用程序和DLL。
class Program
{
static void Main(string[] args)
{
StandardConfigSectionHandler section = StandardConfigSectionHandler.GetConfiguration();
string value = section.Value;
}
}
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>
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; }
}
}
}
什么值我嘗試“ConfigPath”它將返回null,或拋出錯誤說“test”是一個無法識別的元素。 我試過的價值觀:
您的代碼存在一些問題。
你總是在你的GetConfiguration
方法中返回null
,但我會假設這只是問題,而不是你的實際代碼。
更重要的是, ConfigPath
值的格式不正確。 你有一個尾部斜杠ConfigSectionGroup/ConfigSection/
,刪除最后一個斜杠,它將能夠找到該部分。
最重要的是,您在配置系統中聲明您的部分的方式將期望您的“值”存儲在ConfigSection
元素的屬性中。 像這樣
<ConfigSectionGroup> <ConfigSection value="foo" /> </ConfigSectionGroup>
所以,把它們放在一起:
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; }
}
}
要閱讀有關如何配置配置部分的更多信息,請參閱此優秀的MSDN文檔: 如何:使用ConfigurationSection創建自定義配置部分 。 它還包含有關如何在(與測試元素)的子元素中存儲配置值的信息。
我遇到了類似的問題:
ConfigurationManager.GetSection("CompaniesSettings")
我的配置文件:
<section name="CompaniesSettings" type="Swedbank2015.CompaniesSectionReader, Swedbank2015"/>
我收到一個錯誤:
無法加載文件或程序集'Swedbank2015'
我找到了有趣的解決方案,我將類文件移動到一個單獨的項目中(type = Class Library,name = SwBankConfigHelper)。 我將它添加到參考並更改配置文件:
<section name="CompaniesSettings" type=" SwBankConfigHelper.CompaniesSectionReader, SwBankConfigHelper"/>
我的代碼工作正常!
CompaniesConfig = new CompaniesConfig((XmlNodeList)ConfigurationManager.GetSection("CompaniesSettings"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.