扩展web.config

appSettings的两大限制:

1.不能很好的存储结构化的数据

2.处理不同类型的数据灵活性较差

比如你要在配置文件中存储如下信息是不行的:

<orderService available="true" pollTimeout="00:01:00"  location="tcp://OrderComputer:8010/OrderService"/>
为了突破这些限制,你可以这样扩展配置文件:

第一步,把如下代码加入到App_Code或者写成一个DLL

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 string Location
    {
        get { return (string)base["location"]; }
        set { base["location"] = value; }
    }

 第二步,在 <configSections>中注册

   <configSections>
    ...
    <section name="orderService" type="OrderService" />
  </configSections>

 第三步,获取你的自定义信息

 Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
OrderService custSection =  (OrderService)config.GetSection("orderService");

 lblInfo.Text += "获取信息如下...<br />" +
  "<b>位置:</b> " + custSection.Location +
  "<br /><b>可用:</b> " + custSection.Available.ToString() +
  "<br /><b>过期:</b> " + custSection.PollTimeout.ToString() + "<br /><br />";

posted @ 2009-10-30 14:58  wispzone  阅读(377)  评论(3编辑  收藏  举报