自定义配置部分无法识别的属性

时间:2018-08-01 12:08:14

标签: c# web-config

在我的web.config中创建了一个自定义部分,其中包含元素列表。在尝试将属性添加到服务器部分之前,我可以获取服务器列表。我得到了无法识别的属性。

部分

<appSection>
    <!--leave global login and server login blank to prompt user for creds-->
    <servers companyName="Company Name" ignoreCertErrors="true" saveAs="TestFile.rdg" username="" password=""> <!--global login-->
        <server name="test1.local" username="" password="" /> <!--ignore global creds if set per server-->
        <server name="test2.local" username="" password="" /> <!--ignore global creds if set per server-->
    </servers>
</appSection>

ConfigurationSection

public class ServerSection : ConfigurationSection
{
    [ConfigurationProperty("companyName", IsRequired = true)]
    public string CompanyName
    {
        get { return this["companyName"] as string; }
        set { this["companyName"] = value; }
    }

    [ConfigurationProperty("ignoreCertErrors", IsRequired = true)]
    public bool IgnoreCertErrors
    {
        get { return (bool)this["ignoreCertErrors"]; }
        set { this["ignoreCertErrors"] = value; }
    }

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

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

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

    [ConfigurationProperty("servers")]
    public ServerCollection Servers
    {
        get { return this["servers"] as ServerCollection; }
    }
}

无障碍通话

public class ConfigRetriever
{
    private static ServerSection _config = ConfigurationManager.GetSection("appSection") as ServerSection;
    public static List<string> ServerNames
    {
        get
        {
            ServerCollection col = _config.Servers;
            List<string> servers = new List<string>();
            foreach (ServerElement server in col)
            {
                servers.Add(server.Name);
            }
            return servers;
        }
    }

    public ServerCollection Servers
    {
        get { return _config.Servers; }
    }

    public static string CompanyName
    {
        get { return _config.CompanyName; }
    }

    public static bool IgnoreCertErrors
    {
        get { return _config.IgnoreCertErrors; }
    }

    public static string SaveAs
    {
        get { return _config.SaveAs; }
    }

    public static string Username
    {
        get { return _config.Username; }
    }

    public static string Password
    {
        get { return _config.Password; }
    }
}

0 个答案:

没有答案