获取web.config配置文件的sectionGroup
1)web.config 文件内容如下:
<configuration> <configSections> <sectionGroup name="KaiXinSectionGroup"> <section name="KaiXinSection" type="WebApplication1.RewriterConfigSection"/> <!--type 为类RewriterConfigSection的路径--> </sectionGroup> </configSections> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <KaiXinSectionGroup> <KaiXinSection> <add key="AppKey" value="123456"/> <add key="AppSecret" value="111111"/> <add key="SCOPE" value="basic"/> </KaiXinSection> </KaiXinSectionGroup> </configuration>
2)添加一个类文件ConfigurationHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; namespace WebApplication1 { public class ConfigurationHelper { } public class RewriterConfigSection : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public RewriterRuleElementCollection MySection { get { return (RewriterRuleElementCollection)base[""]; } } } public class RewriterRuleElement : ConfigurationElement { [ConfigurationProperty("key", IsRequired = true)] public string Key { get { return (string)base["key"]; } set { base["key"] = value; } } [ConfigurationProperty("value", IsRequired = true)] public string Value { get { return (string)base["value"]; } } } public class RewriterRuleElementCollection : ConfigurationElementCollection { public RewriterRuleElementCollection() { RewriterRuleElement rrElement = CreateNewElement() as RewriterRuleElement; BaseAdd(rrElement); } protected override ConfigurationElement CreateNewElement() { return new RewriterRuleElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((RewriterRuleElement)element).Key; } protected override string ElementName { get { return "add"; } } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } public RewriterRuleElement this[int index] { get { return (RewriterRuleElement)BaseGet(index); } } public new RewriterRuleElement this[string name] { get { return (RewriterRuleElement)BaseGet(name); } } } }
3)获取SessionGroup里的值
public RewriterConfigSection Section { get; set; } protected void Button1_Click(object sender, EventArgs e) { Section = (RewriterConfigSection)ConfigurationManager.GetSection("KaiXinSectionGroup/KaiXinSection"); string a = Section.MySection["AppKey"].Value; string b = Section.MySection["AppSecret"].Value; string c = Section.MySection["SCOPE"].Value; }