cod*_*er1 11 asp.net performance web-config appsettings configsection
我正在编写一个可以使用几个不同主题的页面,我将在web.config中存储有关每个主题的一些信息.
是否更有效地创建一个新的sectionGroup并将所有内容存储在一起,或者只是将所有内容放在appSettings中?
configSection解决方案
<configSections>
<sectionGroup name="SchedulerPage">
<section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
<section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<SchedulerPage>
<Themes>
<add key="PI" value="PISchedulerForm"/>
<add key="UB" value="UBSchedulerForm"/>
</Themes>
</SchedulerPage>
Run Code Online (Sandbox Code Playgroud)
要访问configSection中的值,我使用以下代码:
NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
String SchedulerTheme = themes["UB"];
Run Code Online (Sandbox Code Playgroud)
appSettings解决方案
<appSettings>
<add key="PITheme" value="PISchedulerForm"/>
<add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
要在appSettings中访问值,我正在使用此代码
String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
Run Code Online (Sandbox Code Playgroud)
Nic*_*len 11
对于更复杂的配置设置,我会使用一个自定义配置部分,明确定义每个部分的角色
<appMonitoring enabled="true" smtpServer="xxx">
<alertRecipients>
<add name="me" email="me@me.com"/>
</alertRecipient>
</appMonitoring>
Run Code Online (Sandbox Code Playgroud)
在您的配置类中,您可以使用类似的方式公开属性
public class MonitoringConfig : ConfigurationSection
{
[ConfigurationProperty("smtp", IsRequired = true)]
public string Smtp
{
get { return this["smtp"] as string; }
}
public static MonitoringConfig GetConfig()
{
return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以从代码中以下列方式访问配置属性
string smtp = MonitoringConfig.GetConfig().Smtp;
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 10
在效率方面没有可衡量的差异.
如果您只需要名称/值对,AppSettings就很棒.
对于任何更复杂的东西,值得创建自定义配置部分.
对于您提到的示例,我将使用appSettings.
性能没有区别,因为ConfigurationManager.AppSettings无论如何只调用GetSection("appSettings").如果您需要枚举所有键,那么自定义部分将比枚举所有appSettings并在键上寻找一些前缀更好,但除非您需要比NameValueCollection更复杂的东西,否则更容易坚持使用appSettings.