2013-06-25 36 views
2

这里是的ConfigurationSection类ConfigurationManager.GetSection总是给人对象使用默认值

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整数等)。研究表明这应该很容易,但无济于事我无法弄清楚这一点。

回答

4

您无法使用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; } 
} 
+0

这是肯定的答案。我一定是被以前的开发者抛弃了。他做了一些稍微不同的事。他用正常的get/set backers定义了他的ConfigurationSection类,但是使用configSource属性将它作为xml文件加载到web.config中。谢谢您的帮助。 – pixelshaded