这是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个整数等)。研究表明,这应该很容易做到,但无济于事,我无法弄清楚。
最佳答案
您不能将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; }
}
关于c# - ConfigurationManager.GetSection始终为对象提供默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17287119/