讀取自訂Section區段
自訂Section不是常常做,所以容易忘記...網路上蠻多資料的,不過還是自己整理一下
Web Config 設定有些要注意
type :存取sectiont的程式名稱要含namespace
allowDefinition : 視需求改變(MSDN:SectionInformation.AllowDefinition 屬性)
Web Config 的參考設定如下:
1: <configuration>
2: <configSections>
3: <section name="UserInfo"
4: type="ReadSection.SectionHandler"
5: allowDefinition="Everywhere"/>
6: </configSections>
7: <UserInfo>
8: <ID>12345</ID>
9: <Name>菜鳥工程師</Name>
10: </UserInfo>
11: <connectionStrings/>
12: <system.web></system.web>
13: </configuration>
做一支Class放UserInfo的值
1: public class SectinInfo
2: {
3: private string _id;
4:
5: public string ID
6: {
7: get { return _id; }
8: set { _id = value; }
9: }
10:
11: private string _name;
12:
13: public string Name
14: {
15: get { return _name; }
16: set { _name = value; }
17: }
18: }
重點來了,做一支存取Section的程式,繼承System.Configuration.IConfigurationSectionHandler介面,並實做Create(object parent, object configContext, System.Xml.XmlNode section) 這個方法
1: namespace ReadSection
2: {
3: public class SectionHandler : IConfigurationSectionHandler
4: {
5: public object Create(object parent, object configContext, System.Xml.XmlNode section)
6: {
7: SectinInfo si = new SectinInfo();
8: si.ID = section.SelectSingleNode("ID").InnerText;
9: si.Name = section.SelectSingleNode("Name").InnerText;
10:
11: return si;
12: }
13: }
14: }
最後透過ConfigurationManager.GetSection()這方法取出object,記得Type要指定一下
1: SectinInfo si = (SectinInfo)ConfigurationManager.GetSection("UserInfo");
2: Response.Write(string.Format("{0}({1})", si.Name, si.ID));