Asp.net
將值儲存在 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>要訪問 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;