You might be used to the good old web.config or app.config file. But if you upgrade your solution to something a bit more modern like .Net 5, then it will be transformed to appsettings.json. Here are some tips about how to use the appsettings.json.
The app.config file was stored as an XML file. So you probably used something similar to:
ConfigurationManager.AppSettings["MySettingName"];
Code language: C# (cs)
Or if you want a section:
ConfigurationManager.GetSection("MySection/MySubSection")
Code language: C# (cs)
Getting a simple setting was easy, but creating sections was a bit more annoying.
Now that we can use JSON, everything is easier. You still can store your simple setting, but complex object as well, it’s JSON after all.
To manipulate this new config file, you should install these two NuGet packages:
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Binder
So now let’s say you have a simple setting stored in this appsettings.json file:
{
"MySetting": true
}
Code language: YAML (yaml)
To access it, you can’t use anymore the ConfigurationManager, but instead you could use a little helper class like this one:
public static class ConfigurationHelper
{
public static string GetByName(string configKeyName)
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
IConfigurationSection section = config.GetSection(configKeyName);
return section.Value;
}
}
Code language: C# (cs)
Now you can access your setting with this line:
var mySettingValue = ConfigurationHelper.GetByName("MySetting");
Code language: C# (cs)
But like I said ealier, because it is JSON format, you could store more complex object like this one:
public class MyConfigObject
{
public bool IsEnabled { get; set; };
public string Param1 { get; set; }
public int Param2 { get; set; }
}
Code language: C# (cs)
So in the appsettings.json, it could be stored like this:
{
"MyConfigObject": {
"IsEnabled": true,
"Param1": "this is a string",
"Param2": 123
}
}
Code language: YAML (yaml)
And to access this object from the settings, you could do the following:
var section = config.GetSection(nameof(MyConfigObject));
var myConfigObject = section.Get<MyConfigObject>();
Code language: C# (cs)
Now, if you want to level up your skills, I would recommend to use the IOptions Pattern, there is a pretty good article talking about it here.
Happy coding! 🙂
[…] When everything is done, open your solution in Visual Studio and check if you can build. You might want to verify the config file as well because it will be migrated to a appsettings.json file. So if you were using ConfigurationManager.AppSetting, you will need to do some adaptations as well. […]