配置部分未加载

Config section not loading

我在 web.config 中声明了我的配置部分(在 configSection 元素中):

<section name="gmailEmail" type="MyApp.Communication.Sections.GmailSection" allowLocation="true" allowDefinition="Everywhere" />

和用法:

<gmailEmail>
  <from emailAddress="pat.wasiewicz@gmail.com" name="MyApp"></from>
  <server password="mysuperpass">
</gmailEmail>

我的配置型号:

public class GmailSection : ConfigurationSection
{
    [ConfigurationProperty("server")]
    public ServerElement Server { get; set; }

    [ConfigurationProperty("from")]
    public FromElement From { get; set; }
}

public class ServerElement : ConfigurationElement
{


    [ConfigurationProperty("host", DefaultValue = "smtp.gmail.com", IsRequired = false)]
    public string Host { get; set; }

    [ConfigurationProperty("port", DefaultValue = 587, IsRequired = false)]
    public int Port { get; set; }

    [ConfigurationProperty("ssl", DefaultValue = true, IsRequired = false)]
    public bool Ssl { get; set; }

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

public class FromElement : ConfigurationElement
{
    [ConfigurationProperty("emailAddress", IsRequired = true)]
    public string EmailAddress { get; set; }

    [ConfigurationProperty("name", IsRequired = false)]
    public string Name { get; set; }
}

不幸的是,有一个问题:

var configSection = (GmailSection)ConfigurationManager.GetSection("gmailEmail");

configSection.ServernullconfigSection.Fromnull。为什么?

配置节的类型名称缺少程序集名称

<section name="gmailEmail" type="MyApp.Communication.Sections.GmailSection, MyApp" allowLocation=.....

server/password 元素缺少结束标记 ( /> )

<server password="mysuperpass" />

但我认为这些都是错别字。

你应该改变你所有的{ get;放; } 属性 实现使用相同的键调用基础 class' 索引器。我已经实现了 GmailSection class,你可以用同样的方式修改 ServerElement 和 FormElement classes。

public class GmailSection : ConfigurationSection
{
    [ConfigurationProperty("server")]
    public ServerElement Server
    {
        get
        {
            return (ServerElement)this["server"];
        }
        set
        {
            this["server"] = value;
        }
    }

    [ConfigurationProperty("from")]
    public FromElement From
    {
        get
        {
            return (FromElement)this["from"];
        }
        set
        {
            this["from"] = value;
        }
    }
}