GetSection方法讀取的是configSections節點,這個節點在web.config配置文件中,它比較特殊,必須放置於首節點,也就是說,在它之前不能有其它類型的節點。configSections子節點有section和sectionGroup,后者是前者的集合節點:
<configSections> <section name="CustomConfig" type="OrderMvc.CustomConfig, OrderMvc"/> </configSections>
web.config關於CustomConfig的定義:
<CustomConfig> <Name Value="asdf"/> </CustomConfig>
下面說說它的作用,通過對ConfigurationManager.GetSection(...)方法的調用,如果某個類繼承IConfigurationSectionHandler接口,那么會觸發此接口的Create方法,這樣我們就可以做一些事了。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Xml; namespace OrderMvc { public class CustomConfig : IConfigurationSectionHandler { public string Name { get; private set; } public object Create(object parent, object configContext, XmlNode section) { CustomConfig config = new CustomConfig(); var name = section.SelectSingleNode("Name"); if (name != null && name.Attributes != null) { var attribute = name.Attributes["Value"]; if (attribute != null) config.Name = attribute.Value; } return config; } } }
調用:
var config = ConfigurationManager.GetSection("CustomConfig") as CustomConfig; Debug.WriteLine(config.Name);