ConfigurationManager.GetSection总是为对象提供默认值

本文关键字:默认值 对象 GetSection ConfigurationManager | 更新日期: 2023-09-27 18:19:41

这是ConfigurationSection类

using System.Configuration;
namespace CampusWebStore.Config
{
    public class PoolerConfig : ConfigurationSection
    {
        [ConfigurationProperty("PoolId", IsRequired = true)]
        public string PoolId { get; set; }
        [ConfigurationProperty("Host", IsRequired = true)]
        public string Host { get; set; }
        [ConfigurationProperty("Port", IsRequired = true)]
        public int Port { get; set; }
        [ConfigurationProperty("Enabled", IsRequired = true)]
        public bool Enabled { get; set; }
    }
}

web.config节定义

<section name="PoolerConfig" type="CampusWebStore.Config.PoolerConfig, CampusWebStore"/>

实际区段

<PoolerConfig
    PoolId="asdf-asdf-asdf-asdf"
    Host="localhost"
    Port="5000"
    Enabled="true"
  />

然后加载它的行(在Global.asax.cs中)

PoolerConfig poolerConfig = ConfigurationManager.GetSection("PoolerConfig") as PoolerConfig;

似乎无论我做什么,PoolerConfig中的所有属性都是默认值(空字符串、0 int等)。研究表明,这应该很容易,但我无法弄清楚这一点。

ConfigurationManager.GetSection总是为对象提供默认值

配置属性不能使用get/set支持者。必须访问基类才能操作属性。看见http://msdn.microsoft.com/en-us/library/2tw134k3(v=vs.100).aspx。

更改:

 [ConfigurationProperty("PoolId", IsRequired = true)]
 public string PoolId { get; set; }

收件人:

 [ConfigurationProperty("PoolId", IsRequired = true)]
 public string PoolId 
 {
    get { return (string)this["PoolID"]; }
    set { this["PoolID"] = value; }
 }