<appSetting>元素保存应用程序使用自定义信息。它有两个明显的限制,首先,它不能保存结构化的信息,如列表。
2:它不能灵活的处理各种数据类型。它只能使用单一字符串。
幸好asp.net使用一个模块化的高度可扩展的配置模型。
有三个基本的步骤:
1:确定要配置文件中保存的信息以及如何把他们组织到元素和特性。最理想的是,对于每个概念上相关的设置组都有一个元素,通过特性保存它们。
2:对于每个新元素,创建一个C#类封装它的信息。
3:在配置文件里注册新节。
编码过程:
1:创建Section类
</appSettings>
<connectionStrings/>
<!--<orderService available="true" pollTimeout="00:01:00"
location="tcp://OrderComputer:8010/OrderService"/>-->
<orderService available="true" pollTimeout="00:01:00">
<location computer="OrderComputer" port="8010" endpoint="OrderService"/>
</orderService>
<system.web>
这个是我自定义的<orderService>
public class OrderService : ConfigurationSection
{
[ConfigurationProperty("available",
IsRequired = false, DefaultValue = true)]
public bool Available
{
get { return (bool)base["available"]; }
set { base["available"] = value; }
}
[ConfigurationProperty("pollTimeout",
IsRequired = true)]
public TimeSpan PollTimeout
{
get { return (TimeSpan)base["pollTimeout"]; }
set { base["pollTimeout"] = value; }
}
[ConfigurationProperty("location",
IsRequired = true)]
public Location Location
{
get { return (Location)base["location"]; }
set { base["location"] = value; }
}
}
public class Location : ConfigurationElement
{
[ConfigurationProperty("computer",
IsRequired = true)]
public string Computer
{
get { return (string)base["computer"]; }
set { base["computer"] = value; }
}
[ConfigurationProperty("port",
IsRequired = true)]
public int Port
{
get { return (int)base["port"]; }
set { base["port"] = value; }
}
[ConfigurationProperty("endpoint",
IsRequired = true)]
public string Endpoint
{
get { return (string)base["endpoint"]; }
set { base["endpoint"] = value; }
}
}
可以看到每个属性都使用ConfigurationProperty特性映射到相应的特性名称。
2:注册Section类
<configSections>
<section name="orderService" type="OrderService"/>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Con...
3:如果调用
Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(
Request.ApplicationPath );
OrderService custSection = (OrderService)config.GetSection("orderService");
lblInfo.Text += "Retrieved service information...<br />" +
"<b>Location (computer):</b> " + custSection.Location.Computer +
"<br /><b>Available:</b> " + custSection.Available.ToString() +
"<br /><b>Timeout:</b> " + custSection.PollTimeout.ToString() + "<br /><br />";
结果:
Location (computer): OrderComputer
Available: True
Timeout: 00:01:00
This page was served at 2010-11-16 8:06:26