【发布时间】:2009-12-28 08:54:28
【问题描述】:
解决方案: 只是添加解决方案:sectionGroups 似乎没有属性。正确的方法似乎是将ConfigurationSection 作为父母,将ConfigurationElement 作为每个孩子。还有 ConfigurationElementCollection 用于收藏。 .net Framework 中的一个示例:<roleManager> 是一个 Section,<providers> 是一个 ElementCollection。我blogged about my solution。
原始问题:我的 web.config 中有一个自定义 sectionGroup:
<sectionGroup name="myApp" type="MyApp.MyAppSectionGroup">
<section name="localeSettings"
type="MyApp.MyAppLocaleSettingsSection"/>
</sectionGroup>
sectionGroup 本身应该有一个属性:
<myApp defaultModule="MyApp.MyAppTestNinjectModule">
<localeSettings longDateFormat="MM/dd/yyyy HH:mm:ss" />
</myApp>
我无法访问该属性 (defaultModule)。使用ConfigurationManager.GetSection("myApp/localeSettings") 获取一个部分非常容易,并将其转换为从 ConfigurationSection 继承的类。
但我似乎无法轻松访问 sectionGroup,因为 ConfigurationManager.GetSection("myApp") 返回 null。我试过ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["myApp"],但这并没有实现一个索引器,让我可以访问defaultModule。
我是不是误会了什么? sectionGroups 真的只是没有自己设置的容器吗?我可以在没有 sectionGroup 的情况下嵌套部分吗? OpenExeConfiguration 适合 .net 应用程序(使用 web.config)还是只适合 app.config 的?
编辑:感谢有关 WebConfigurationManager 而不是 ConfigurationManager 的提示。这并没有解决我的主要问题,但至少这有更明智的命名 OpenXXX 方法。
目前,这是两个类。 LocaleSettings 工作得很好,只是 SectionHandler 不允许我访问“defaultModule”属性。
public class MyAppSectionGroup: ConfigurationSectionGroup
{
[ConfigurationProperty("localeSettings")]
public MyAppLocaleSettingsSection LocaleSettings
{
get
{
return Sections["localeSettings"] as MyAppLocaleSettingsSection;
}
}
}
public class MyAppLocaleSettingsSection: ConfigurationSection
{
[ConfigurationProperty("longDateFormat", DefaultValue = "yyyy-MM-dd HH:mm")]
public string LongDateFormat
{
get
{
return this["longDateFormat"] as string;
}
}
}
【问题讨论】:
标签: .net asp.net web-config