在 web.config 中存储值 - appSettings 或 configSection - 哪个更有效?

2024-01-26

我正在编写一个可以使用几个不同主题的页面,并且我将在 web.config 中存储有关每个主题的一些信息。

创建一个新的sectionGroup并将所有内容存储在一起,还是将所有内容都放在appSettings中,是否更有效?

配置部分解决方案

<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>

要访问 configSection 中的值,我使用以下代码:

    NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
    String SchedulerTheme = themes["UB"];

应用程序设置解决方案

<appSettings>
    <add key="PITheme" value="PISchedulerForm"/>
    <add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>

要访问 appSettings 中的值,我使用此代码

    String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();

对于更复杂的配置设置,我将使用自定义配置部分,它清楚地定义了每个部分的角色,例如

<appMonitoring enabled="true" smtpServer="xxx">
  <alertRecipients>
    <add name="me" email="m[email protected] /cdn-cgi/l/email-protection"/>
  </alertRecipient>
</appMonitoring>

在您的配置类中,您可以使用类似的内容公开您的属性

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
  }
}

然后,您可以通过以下方式从代码中访问配置属性

string smtp = MonitoringConfig.GetConfig().Smtp;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 web.config 中存储值 - appSettings 或 configSection - 哪个更有效? 的相关文章

随机推荐