当前位置: 首页 > 编程语言 > C#

使用.Net配置框架加载具有所需子ConfigurationElement的ConfigurationSection分享

时间:2023-04-11 02:10:26 C#

C#学习教程:使用.Net配置框架加载具有所需子配置元素的ConfigurationSection来自web.config文件的CustomConfigurationSection。自定义配置部分具有所需的自定义配置元素。这意味着当我加载配置部分时,如果配置中不存在该配置元素,我希望看到一个异常。问题是.NET框架似乎完全忽略了isRequired属性。因此,当我加载配置部分时,我只需创建一个自定义配置元素的实例并将其设置在配置部分中。我的问题是,为什么会这样?我希望GetSection()方法触发ConfigurationErrorsexception,因为配置中缺少必需的元素。这就是我的配置部分的样子。公共类MyConfigSection:ConfigurationSection{[ConfigurationProperty("MyConfigElement",IsRequired=true)]publicMyConfigElementMyElement{get{return(MyConfigElement)this["MyConfigElement"];}}}publicclassMyConfigElement(MyConfigElement":ConfigurationElement{[,IsRequired=true)]publicstringMyAttribute{get{returnthis["MyAttribute"].ToString();}}}这就是我加载配置部分的方式。classProgram{publicstaticConfigurationOpenConfigFile(stringconfigPath){varconfigFile=newFileInfo(configPath);varvdm=newVirtualDirectoryMapping(configFile.DirectoryName,true,configFile.Name);varwcfm=newWebConfigurationFileMap();wcfm.虚拟目录。添加("/",vdm);返回WebConfigurationManager。OpenMappedWebConfiguration(wcfm,“/”);}staticvoidMain(string[]args){try{stringpath=@"C:UsersvrybakDesktopWeb.config";varconfigManager=OpenConfigFile(路径);varconfigSection=configManager.GetSection("MyConfigSection")asMyConfigSection;MyConfigElementelem=configSection.MyElement;}catch(ConfigurationErrorsExceptionex){Console.WriteLine(ex.ToString());这是我的配置文件的样子。奇怪的是,如果我打开配置文件并连续加载该部分2次,我会得到我期望的异常。varconfigManager=OpenConfigFile(路径);varconfigSection=configManager.GetSection("MyConfigSection")asMyConfigSection;configManager=OpenConfigFile(路径);configSection=configManager.GetSection("MyConfigSection")asMyConfigSection;如果我使用上面的代码,那么将触发异常并告诉我需要MyConfigElement。问题是为什么不在第一时间抛出这个异常?Eric在MS论坛上回答了这个问题并引用了他的回答:ConfigurationPropertyAttribute的IsRequired成员在应用于子对象(从ConfigurationElement派生)时不起作用我发现的最佳解决方法是手动迭代ConfigurationElement类型的所有嵌套属性,并检查拿到那部分后自己做。如果需要一个元素但文件中不存在,我只是抛出一个ConfigurationErrorsException。这是我的代码。privatevoidProcessMissingElements(ConfigurationElementelement){foreach(PropertyInformationpropertyInformationinelement.ElementInformation.Properties){varcomplexProperty=propertyInformation.ValueasConfigurationElement;如果(complexProperty==null)继续;如果(propertyInformation.IsRequired&&!complexProperty.ElementInformation.IsPresent)thrownewConfigurationErrorsException("ConfigProperty:[{0}]是必需的但不存在".FormatStr(propertyInformation.Name));如果(!complexProperty.ElementInformation.IsPresent)propertyInformation.Value=null;否则ProcessMissingElements(复杂属性);您是否尝试过将其直接分配给正确类型的变量,即MyConfigSection而不是var?这是我在两行代码之间看到的唯一区别。(即在第二行中,var现在采用特定类型)。以上就是C#学习教程:使用.Net配置框架加载ConfigurationSection共享的所有内容,以及需要的子ConfigurationElement。如果对你有用,需要了解更多C#学习教程,希望大家多加关注——本文来自网络合集,不代表立场,如涉及侵权,请点击右转联系管理员删除。如需转载请注明出处: