Custom .NET configuration section.

I am trying to create a custom configuration section to store some API credentials after the tutorial at: http://devlicio.us/blogs/derik_whittaker/archive/2006/11/13/app-config-and-custom-configuration-sections.aspx . I added the following to the Web.config file:

<!-- Under configSections --> <section name="providers" type="EmailApiAccess.Services.ProviderSection, EmailApiAccess.Services"/> <!-- Root Level --> <providers> <add name="ProviderName" username="" password ="" host="" /> </providers> 

and created the following classes:

 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; } } } 

However, when I try to implement code using this:

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

I get a message that "Object" does not contain a definition for "Providers" ....

Any help would be greatly appreciated.

+4
source share
1 answer

ConfigurationManager.GetSection returns a value of type object , not a custom configuration section. Try the following:

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

Source: https://habr.com/ru/post/1502524/


All Articles