65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET自定义Web配置文件节

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.14/5 (4投票s)

2009年1月18日

CPOL

4分钟阅读

viewsIcon

44626

downloadIcon

519

学习如何为代码库定义和使用您自己的web.config节。

引言

web.config在Web开发中是一个非常有用的工具。它允许您放置可由您的网站访问并更改的设置,而无需重新部署代码。但是,当您想要构建一个代码库并为该库设置web.config设置时会发生什么?当然,您可以使用标准的<appSettings>节,但还有另一种方法。您可以创建一个自定义的web.config节。

背景

我相信让一切(在合理的范围内)可重用非常重要。您在一个以上项目中使用的任何内容都应该放在可重用的代码库中。任何您想进行单元测试或通过FXCop运行的内容都应该在其自己的类库中。此外,我相信这些代码库应该有一种方法来更改其设置,以使其能够在多种情况下使用。

但是,如果您有一个可以在ASP.NET网站和Windows应用程序中使用的库呢?如果您使用System.Configuration.ConfigurationManager.AppSettings["Key"],它实际上会引用web.configapp.config中的同一键。这是一种非常简单易行的方法,但这篇文章是关于创建自定义Web配置的。我还没有测试过,但这个自定义节可能在应用程序配置中有效,也可能无效。本文将重点介绍在Web环境中使用自定义配置。

定义属性

第一步是确定要公开哪些设置。一旦确定要公开的内容,就可以创建ConfigurationSection定义类了。在我的缓存库的情况下,我将其称为CacheConfiguration。请注意,它必须扩展自System.Configuration.ConfigurationSection

public class CacheConfiguration : ConfigurationSection

接下来是定义属性。对于此类,我公开对应于与缓存优先级关联的节的时间长度的整数值。下面是一个属性示例

// Number Property
[ConfigurationProperty("highPriority", DefaultValue = 60, IsRequired = false)]
[IntegerValidator(MinValue = 0)]
public int HighPriority
{
    get
    { return (int)this["highPriority"]; }
}

ConfigurationProperty是属性的定义,包括名称、默认值以及属性是否必需。IntegerValidator允许我定义最小值,在本例中为零。

您应该注意的一件事是,属性名称(highPriority)在web.config中区分大小写。

访问属性

为了方便自己,我创建了一个Configuration类,它充当配置节的包装器。这使得属性更容易访问,只需简单地引用一个静态类,而不必每次需要访问时都创建配置节的实例。

public static class Configuration
{
    public static CacheConfiguration CacheConfiguration
    {
        get
        {
            CacheConfiguration config = (CacheConfiguration)
              System.Configuration.ConfigurationManager.GetSection("olympus/cache");

            return config;
        }
    }
}

您注意到节点声明了吗?字符串参数"olympus/cache"告诉GetSection我的属性位于哪个节点。如果我想将我的配置放在<system.web>内,我可以将其更改为"system.web/cache"。我更喜欢将我的部分放在它自己的包装器中。

Web.Config - 声明节

<configuration>
    <configSections>
    <sectionGroup name="olympus">
      <section name="cache" type="Olympus.Caching.CacheConfiguration" 
        allowLocation="true" allowDefinition="Everywhere"/>
    </sectionGroup>
</configSections>
...

<configSections>块下面,在<configuration>内,而不是在<system.web>内,放置带有其值的属性。

<olympus>
    <cache highPriority="360"  />
</olympus>

元素集合

所以,现在您已经对自定义配置有了基本的了解,让我们继续学习一些更高级的内容。如果您想要一个元素集合,例如站点使用的cookie集合,该怎么办?好吧,只需添加一个ConfigurationElementCollection类并将ConfigurationSection包装到集合中,并进行一些修改,就可以创建一个看起来像这样的web.config

<olympus>
    <cookie>
      <cookies>
        <add name="My_Cookie_1" enableEncryption="true" timeout="4200" />
        <add name="My_Cookie_2" enableEncryption="true" timeout="4200" />
      </cookies>
    </cookie>
</olympus>

我们只需要添加一个ConfigurationElementCollection类来将ConfigurationSection包装到一个集合中。我已经构建了一个类来处理使用Rijndael、Triple DES或DES(用户选择)加密的cookie,但是加密和cookie是另一天要讨论的话题。

public class CookieConfig : ConfigurationSection

CookieConfig是包含属性的类。这与CacheConfiguration完全相同。

public class CookieCollectionConfiguration : ConfigurationElementCollection
{

    public CookieConfig this[int index]
    {
        get
        {
            return base.BaseGet(index) as CookieConfig;
        }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    public CookieConfig this[string name]
    {
        get
        {
            return base.BaseGet(name) as CookieConfig;
        }
        set
        {
            int index = -1;
            if (base.BaseGet(name) != null)
            {
                index = base.BaseIndexOf(base.BaseGet(name));
                base.BaseRemove(name);
            }

            if (index == -1)
            {
                this.BaseAdd(value);
            }
            else
            {
                this.BaseAdd(index, value);
            }
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new CookieConfig();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((CookieConfig)element).Name;
    } 
}

就是这样,为您的代码库创建自定义web.configuration节。我建议创建一个包含所有已定义字段的web.config节示例,并将该文件包含在代码库项目中。这将使您在将库添加到新的Web应用程序时,更容易弄清楚如何使用自定义配置。自定义节的一个问题是您只有自己创建的文档,并且没有智能感知支持。

© . All rights reserved.