When developing with ASP.NET, the WebApplication builder reads configuration files and provides access via the ConfigurationManager
class. Typically, developers do not manually read and deserialize JSON configuration files into custom classes.
For small configuration files, direct access is manageable. However, when configurations become more complex with multiple properties, mapping them to a class improves maintainability and readability.
Consider the following appsettings.json
file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MyConfig": {
"Host": "localhost",
"Port": 4500
}
}
To retrieve the values for Host
and Port
, you would use the following code:
var host = builder.Configuration["MyConfig:Host"];
var port = int.Parse(builder.Configuration["MyConfig:Port"]);
Instead of accessing individual values directly, you can define a class and map the configuration section to an instance of that class:
public class MyConfig
{
public string Host { get; set; }
public int Port { get; set; }
}
Then, retrieve the configuration as an instance of MyConfig
:
using Newtonsoft.Json.Linq;
var myconfig = builder.Configuration.GetSection("MyConfig").Get<MyConfig>();
var host = myconfig.Host;
var port = myconfig.Port;
When dealing with configurations that have numerous properties or nested structures, using a mapped class simplifies management and improves maintainability.
ยฉ 2025 juniyunapapa@gmail.com.