IConfigurationSectionHandler

IConfigurationSectionHandler

IConfigurationSectionHandler

处理对特定的配置节的访问。

示例代码:

  public class MyConfig : IConfigurationSectionHandler
{
public int MyNum1 { get; set; }
public int MyNum2 { get; set; }
public int MyNum3 { get; set; } public MyConfig()
{
MyNum1 = ;
MyNum2 = ;
MyNum3 = ;
}
// implement interface member
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
try
{
MyConfig options = new MyConfig();
if (section == null) return options; foreach (XmlNode node in section.ChildNodes)
{
if (node.Name == "MyNum1")
options.MyNum1 = int.Parse(node.InnerText);
else if (node.Name == "MyNum2")
options.MyNum2 = int.Parse(node.InnerText);
else if (node.Name == "MyNum3")
options.MyNum3 = int.Parse(node.InnerText);
}
return options;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} }
}

Web.config配置:

<section name="MyConfig" type="WebApp.MyConfig" />

及
 <MyConfig>
<MyNum1>111</MyNum1>
<MyNum2>222</MyNum2>
<MyNum3>333</MyNum3>
</MyConfig>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="MyConfig" type="WebApp.MyConfig" />
</configSections>
<MyConfig>
<MyNum1></MyNum1>
<MyNum2></MyNum2>
<MyNum3></MyNum3>
</MyConfig>

调用:

 var myconfig = WebConfigurationManager.GetSection("MyConfig") as MyConfig;
Response.Write(myconfig.MyNum2);

参考:

https://stackoverflow.com/questions/3694253/how-to-use-iconfigurationsectionhandler-for-global-configuration/28060401#28060401

05-18 20:25