从ConfigurationElement访问ConfigurationSection

时间:2010-05-19 10:21:14

标签: c# asp.net

我有一个映射web.config的配置类,类似于:

 public class SiteConfigurationSection : ConfigurationSection 
    {
        [ConfigurationProperty("defaultConnectionStringName", DefaultValue = "LocalSqlServer")]
        public string DefaultConnectionStringName
        {
            get { return (string)base["defaultConnectionStringName"]; }
            set { base["defaultConnectionStringName"] = value; }
        }

        [ConfigurationProperty("Module", IsRequired = true)]
        public ModuleElement Module
        {
            get { return (ModuleElement)base["Module"]; }
        }
    }

    public class ModuleElement : ConfigurationElement
    {
        [ConfigurationProperty("connectionStringName")]
        public string ConnectionStringName
        {
            get { return (string)base["connectionStringName"]; }
            set { base["connectionStringName"] = value; }
        }

        public string ConnectionString
        {
            get
            {
                string str;
                if (string.IsNullOrEmpty(this.ConnectionStringName))
                {
                     str =//GET THE DefaultConnectionStringName from SiteConfigurationSection;
                }
                else 
                     str = this.ConnectionStringName;

                return WebConfigurationManager.ConnectionStrings[str].ConnectionString;
            }
        }      

    }

如果在web.config文件的Module部分中缺少连接字符串名称值,则应该从配置部分读取该值。

怎么做?

1 个答案:

答案 0 :(得分:0)

这取决于部分标签的名称。

 var cs = 
    ((SiteConfigurationSection)WebConfigurationManager
      .GetSection("mySectionTag")).DefaultConnectionString;