代码之家  ›  专栏  ›  技术社区  ›  Dave Anderson

如何使用属性的潜在子元素和属性定义自定义web.config节?

  •  62
  • Dave Anderson  · 技术社区  · 18 年前

    我开发的web应用程序通常需要相互依赖的配置设置,而且随着我们在每个环境之间的移动,有些设置也必须更改。

    目前,我们所有的设置都是简单的键值对,但是创建自定义配置部分会很有用,这样当两个值需要一起更改或者当环境的设置需要更改时,就可以很明显地看到这一点。

    创建自定义配置节的最佳方法是什么?在检索值时是否有任何特殊注意事项?

    6 回复  |  直到 5 年前
        1
  •  83
  •   Timothy S. Van Haren Prashant    9 年前

    使用属性、子配置节和约束

    还可以使用自动处理管道的属性,并提供轻松添加约束的能力。

    namespace Ani {
    
        public sealed class MailCenterConfiguration : ConfigurationSection
        {
            [ConfigurationProperty("userDiskSpace", IsRequired = true)]
            [IntegerValidator(MinValue = 0, MaxValue = 1000000)]
            public int UserDiskSpace
            {
                get { return (int)base["userDiskSpace"]; }
                set { base["userDiskSpace"] = value; }
            }
        }
    }
    

    这是在web.config中设置的,如下所示

    <configSections>
        <!-- Mailcenter configuration file -->
        <section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/>
    </configSections>
    ...
    <mailCenter userDiskSpace="25000">
        <mail
         host="my.hostname.com"
         port="366" />
    </mailCenter>
    

    子元素

    邮政 在与上述文件相同的.cs文件中创建。在这里,我对端口添加了约束。如果为端口分配了一个不在此范围内的值,则在加载配置时运行时将发出抱怨。

    MailCenterConfiguration.cs:

    public sealed class MailCenterConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("mail", IsRequired=true)]
        public MailElement Mail
        {
            get { return (MailElement)base["mail"]; }
            set { base["mail"] = value; }
        }
    
        public class MailElement : ConfigurationElement
        {
            [ConfigurationProperty("host", IsRequired = true)]
            public string Host
            {
                get { return (string)base["host"]; }
                set { base["host"] = value; }
            }
    
            [ConfigurationProperty("port", IsRequired = true)]
            [IntegerValidator(MinValue = 0, MaxValue = 65535)]
            public int Port
            {
                get { return (int)base["port"]; }
                set { base["port"] = value; }
            }
    

    要在代码中实际使用它,只需实例化MailCenterConfigurationObject,这将 请阅读web.config中的相关章节。

    private static MailCenterConfiguration instance = null;
    public static MailCenterConfiguration Instance
    {
        get
        {
            if (instance == null)
            {
                instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter");
            }
    
            return instance;
        }
    }
    

    另一个文件.cs

    public void SendMail()
    {
        MailCenterConfiguration conf = MailCenterConfiguration.Instance;
        SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port);
    }
    

    我之前提到过,当加载配置并且某些数据不符合您设置的规则(例如,在MailCenterConfiguration.cs中)时,运行时会抱怨。我倾向于在我的网站启动时尽快了解这些事情。解决此问题的一种方法是将配置加载到_Global.asax.cx.Application_Start _中,如果配置无效,将通过异常通知您。您的站点不会启动,相反,您将在 Yellow screen of death

    Global.asax.cs

    protected void Application_ Start(object sender, EventArgs e)
    {
        MailCenterConfiguration.Instance;
    }
    
        2
  •  13
  •   Ishmaeel    18 年前

    快而不脏:

    首先创建您的 配置部分

    public class MyStuffSection : ConfigurationSection
    {
        ConfigurationProperty _MyStuffElement;
    
        public MyStuffSection()
        {
            _MyStuffElement = new ConfigurationProperty("MyStuff", typeof(MyStuffElement), null);
    
            this.Properties.Add(_MyStuffElement);
        }
    
        public MyStuffElement MyStuff
        {
            get
            {
                return this[_MyStuffElement] as MyStuffElement;
            }
        }
    }
    
    public class MyStuffElement : ConfigurationElement
    {
        ConfigurationProperty _SomeStuff;
    
        public MyStuffElement()
        {
            _SomeStuff = new ConfigurationProperty("SomeStuff", typeof(string), "<UNDEFINED>");
    
            this.Properties.Add(_SomeStuff);
        }
    
        public string SomeStuff
        {
            get
            {
                return (String)this[_SomeStuff];
            }
        }
    }
    

    然后让框架知道如何在中处理配置类 web.config :

    <configuration>
      <configSections>
        <section name="MyStuffSection" type="MyWeb.Configuration.MyStuffSection" />
      </configSections>
      ...
    

      <MyStuffSection>
        <MyStuff SomeStuff="Hey There!" />
      </MyStuffSection>
    

    然后您可以在代码中使用它,因此:

    MyWeb.Configuration.MyStuffSection configSection = ConfigurationManager.GetSection("MyStuffSection") as MyWeb.Configuration.MyStuffSection;
    
    if (configSection != null && configSection.MyStuff != null)
    {
        Response.Write(configSection.MyStuff.SomeStuff);
    }
    
        3
  •  5
  •   LordHits    12 年前

    有一个极好的例子 example on MSDN ConfigurationCollection 和.NET 4.5,用于web.config中具有配置项列表的自定义节。

        4
  •  4
  •   bhavik bhavik    17 年前

    自定义配置是非常方便的事情,应用程序通常最终需要一个可扩展的解决方案。

    http://aspnet.4guysfromrolla.com/articles/020707-1.aspx

    注意:上述解决方案也适用于.NET2.0。

    http://aspnet.4guysfromrolla.com/articles/032807-1.aspx

        5
  •  3
  •   John Downey    18 年前

    您可以使用节处理程序来实现这一点。这里有一个基本的概述,介绍如何在 http://www.codeproject.com/KB/aspnet/ConfigSections.aspx 然而,它指的是app.config,这与在web.config中编写一个应用程序非常相似。这将允许您在配置文件中拥有自己的XML树,并执行一些更高级的配置。

        6
  •  2
  •   Mike    9 年前

    我发现最简单的方法是使用 appSettings section .

    1. 将以下内容添加到Web.config:

      <appSettings>
          <add key="MyProp" value="MyVal"/>
      </appSettings>
      
    2. 从您的代码访问

      NameValueCollection appSettings = ConfigurationManager.AppSettings;
      string myPropVal = appSettings["MyProp"];
      
    推荐文章