我有一個控制檯應用程序試圖從web.config文件加載CustomConfigurationSection。使用.Net配置框架加載具有必需子ConfigurationElement的ConfigurationSection
自定義配置部分有一個需要的自定義配置元素。這意味着當我加載配置部分時,如果該配置元素不存在於配置中,我希望看到一個異常。問題是.NET框架似乎完全忽略了isRequired屬性。所以當我加載配置部分時,我只是創建了一個自定義配置元素的實例,並將其設置在配置部分。
我的問題是,爲什麼會發生這種情況?我想讓GetSection()方法觸發ConfigurationErrors異常,因爲配置中缺少必需的元素。
這是我的配置部分的外觀。
public class MyConfigSection : ConfigurationSection
{
[ConfigurationProperty("MyConfigElement", IsRequired = true)]
public MyConfigElement MyElement
{
get { return (MyConfigElement) this["MyConfigElement"]; }
}
}
public class MyConfigElement : ConfigurationElement
{
[ConfigurationProperty("MyAttribute", IsRequired = true)]
public string MyAttribute
{
get { return this["MyAttribute"].ToString(); }
}
}
這裏是我如何加載config部分。
class Program
{
public static Configuration OpenConfigFile(string configPath)
{
var configFile = new FileInfo(configPath);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
}
static void Main(string[] args)
{
try{
string path = @"C:\Users\vrybak\Desktop\Web.config";
var configManager = OpenConfigFile(path);
var configSection = configManager.GetSection("MyConfigSection") as MyConfigSection;
MyConfigElement elem = configSection.MyElement;
} catch (ConfigurationErrorsException ex){
Console.WriteLine(ex.ToString());
}
}
這是我的配置文件的樣子。
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="MyConfigSection" type="configurationFrameworkTestHarness.MyConfigSection, configurationFrameworkTestHarness" />
</configSections>
<MyConfigSection>
</MyConfigSection>
奇怪的部分是,如果我打開配置文件並連續加載部分2次,我會得到我期望的異常。
var configManager = OpenConfigFile(path);
var configSection = configManager.GetSection("MyConfigSection") as MyConfigSection;
configManager = OpenConfigFile(path);
configSection = configManager.GetSection("MyConfigSection") as MyConfigSection;
如果我使用上面的代碼,那麼異常將觸發並告訴我MyConfigElement是必需的。問題是爲什麼第一次不拋出這個異常?
我不認爲Eric正確回答了這個問題。你可以在這裏看到我對他的迴應。 http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/710c69e7-0c70-4905-8a5d-448c1e12a2e5?prof=required – 2010-03-19 12:48:37
奇怪的是,它第二次工作。調試.NET框架代碼以查看底層發生了什麼會很有趣。 -dave – 2010-03-21 23:48:11