这是在 web.config 中使用我们自己的配置类的示例。
假设我们有一个要在 web.config 中初始化并在我们的代码中使用的类。
这是我们的课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
namespace MyProject.MyConfigSection
{
public class MyConfig:System.Configuration.IConfigurationSectionHandler
{
public int MyNum1 { get; set; }
public int MyNum2 { get; set; }
public int MyNum3 { get; set; }
public MyConfig()
{
MyNum1 = 0;
MyNum2 = 0;
MyNum3 = 0;
}
//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 System.Configuration.ConfigurationException(
"Error loading startup default options", ex, section);
}
}
}
}
现在我们在 web.config 中用名称声明它。
<configuration>
<configSections>
<section name="MYTESTCONFIGSECTION" type="MyProject.MyConfigSection.MyConfig" />
.... //other sections
.... //other sections
</configSections>
现在在 web.config 本身中,我们将其添加到配置标签之间的任何位置:
<MYTESTCONFIGSECTION>
<MyNum1>111</MyNum1>
<MyNum2>222</MyNum2>
<MyNum3>333</MyNum3>
</MYTESTCONFIGSECTION>
</configuration>
现在我们可以通过如下代码访问此部分:
var myconfig = System.Web.Configuration.WebConfigurationManager.GetSection("MYTESTCONFIGSECTION") as MyConfigSection.MyConfig;
myconfig.MyNum1;
myconfig.MyNum2;
myconfig.MyNum3;
希望这对某人有所帮助。