我正在编写一个可以使用几个不同主题的页面,我将在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>

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

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

appSettings解决方案

<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="me@me.com"/>
  </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;

其他提示

在效率方面没有可衡量的差异。

如果你需要的只是名字/价值对,AppSettings很棒。

对于任何更复杂的事情,值得创建一个自定义配置部分。

对于您提到的示例,我将使用appSettings。

性能没有区别,因为ConfigurationManager.AppSettings无论如何只调用GetSection(“appSettings”)。如果您需要枚举所有键,那么自定义部分将比枚举所有appSettings并在键上寻找一些前缀更好,但除非您需要比NameValueCollection更复杂的东西,否则更容易坚持使用appSettings。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top