2

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

4

1 回答 1

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; }
 }
于 2013-06-25T00:22:43.333 回答