10 Oct 2016
When developing .NET applications, you may want to have some settings stored in your config file so you can change the behaviour of the application without changing the code.
If you have just a couple of settings to include in the config, you could just use appSettings.
This is fine as long as you don't have lots of settings, if you do, you would be better off putting those settings in a custom configuration section. This post will show you how to do that.
<configSections> <section name="CodeShare" type="CodeShare.Library.Config.Section" /> </configSections>
The name is the name you will use for this section lower down in the web.config file.
The type is defined by the namespace and class name for your Section.cs file.
<CodeShare> <website domainAddress="http://www.codeshare.co.uk"/> </CodeShare>
For each of the elements inside the custom section, you want to create a class for it.
using System.Configuration; namespace CodeShare.Library.Config.Elements { public class Website : ConfigurationElement { [ConfigurationProperty("domainAddress", IsRequired = true)] public string domainAddress { get { return (string)this["domainAddress"]; } set { this["domainAddress"] = value; } } } }
As you can see, this needs to use the namespace System.Configuration, you need to add a reference to this in your project:
You need to create a class to represent the configuration section, so it will have properties inside it for the elements in the section, i.e. Website
Now go to the Section.cs Class we created and add the following code:
using System.Configuration;
namespace CodeShare.Library.Config
{
public class Section : ConfigurationSection
{
public static Section Get()
{
return (Section)ConfigurationManager.GetSection("CodeShare");
}
[ConfigurationProperty("website", IsRequired = true)]
public Elements.Website website
{
get { return (Elements.Website)this["website"]; }
set { this["website"] = value; }
}
}
}
inside your controller class or elsewhere when you might need to access config properties, you can now add this private static variable
private static Library.Config.Section config
{
get { return Library.Config.Section.Get(); }
}
Or if you just want to use it once in one method you could do this instead
Library.Config.Section config = Library.Config.Section.Get();
string domainAddress = config.website.domainAddress;
With this you can now add your own custom configuration section to your web.config file and access it in code.
If you found this helpful, please share it with others and I would love to hear from you in the comments.
If you'd like to improve your .NET skills, have a look at the courses on Pluralsight