【问题标题】:Custom Config Section .NET自定义配置部分 .NET
【发布时间】:2013-09-21 06:48:33
【问题描述】:

我正在尝试创建一个自定义配置部分,以按照以下教程保存一些 API 凭据:http://devlicio.us/blogs/derik_whittaker/archive/2006/11/13/app-config-and-custom-configuration-sections.aspx。我已将以下内容添加到我的 Web.config 文件中:

<!-- Under configSections -->
 <section name="providers" type="EmailApiAccess.Services.ProviderSection, EmailApiAccess.Services"/>

<!-- Root Level -->
<providers>
    <add name="ProviderName" username="" password ="" host="" />
  </providers>

并创建了以下类:

public class ProviderSection: ConfigurationSection
{
    [ConfigurationProperty("providers")]
    public ProviderCollection Providers
    {
        get { return ((ProviderCollection)(base["providers"])); }
    }
}
[ConfigurationCollection(typeof(ProviderElement))]
public class ProviderCollection : ConfigurationElementCollection
{
    public ProviderElement this[int index]
    {
        get { return (ProviderElement) BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
                BaseRemoveAt(index);

            BaseAdd(index, value);
        }
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((ProviderElement)(element)).name;
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new ProviderElement();
    }
}
public class ProviderElement: ConfigurationElement
{
    public ProviderElement() { }

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

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

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

    [ConfigurationProperty("host", DefaultValue = "",  IsRequired = false)]
    public string host
    {
        get { return (string)this["host"]; }
        set { this["host"] = value; }
    }


}

但是,当我尝试使用此代码实现代码时:

var section = ConfigurationManager.GetSection("providers");
ProviderElement element = section.Providers["ProviderName"];
var creds = new NetworkCredential(element.username, element.password);   

我收到一条错误消息,提示“对象”不包含“提供者”的定义......

任何帮助将不胜感激。

【问题讨论】:

    标签: c# web-config configurationmanager


    【解决方案1】:

    ConfigurationManager.GetSection 返回 object 类型的值,而不是您的自定义配置部分。请尝试以下操作:

    var section = ConfigurationManager.GetSection("providers") as ProviderSection;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-25
      • 2013-12-05
      • 2014-02-14
      • 2010-11-12
      • 2013-09-17
      • 2011-07-04
      • 2012-12-12
      相关资源
      最近更新 更多