Introduction
In this article, we will learn how to Read Appsettings.json values in .NET Core
Appsettings.json file
The Appsettings.json file stores the application configuration in the .NET core. It's a JSON file that holds the key: value pair.
In this article, we are going to discuss how to read different types of data from app settings.
- Connection String
- Key, value pair
- Object JSON data
- Array JSON data
IConfiguration is an interface provided by Microsoft.Extensions.Configuration library in. NET Core. It's a fundamental part of the .NET configuration system and is commonly used to read configuration settings from various sources, including appsettings.json files.
The above screenshot shows the IConfiguration interface, and it has methods like GetChildren, GetReloadToken, and GetSection. We will go into detail about each method and its usage.
- this[string key]: Gets or sets a configuration value.
- GetChildren(): Gets the immediate descendant configuration sub-sections.
- GetReloadToken(): Returns IChangeToken, which can be used to observe when this configuration is reloaded.
- GetSection(string key): Gets a configuration sub-section with the specified key.
Sample Appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLConnection": "Server=(localdb);Database=db_name;Trusted_Connection=True;"
},
"MyKey": "MyValue",
"Smtp": {
"Server": "mail.whatever.com",
"Port": 25,
"FromAddress": "[email protected]"
},
"AppsettingGroup": {
"Regions": [
{
"Id": 1,
"Code": "EMEA",
"DisplayName": "Europe, Middle East, and Africa"
},
{
"Id": 2,
"Code": "APAC",
"DisplayName": "Asia Pacific"
}
]
}
}
Now we try to read these values one by one.
1. Read "ConnectionString", "key, and value": If we want to read the connection string, then we first need to inject the IConfigration into the Controller or Service class where we need to read this value as shown below.
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
public EmployeeController(IConfiguration configuration)
{
// 1. Reading connection string
string connectionString = configuration.GetConnectionString("SQLConnection");
//2. Reading key;value pair using Key
string myValue = configuration["MyKey"];
}
}
2. Read JSON Object using Option Pattern(Preferred Approach): Let's try to read the SMTP details as shown in the above appsettings.json. The options pattern uses classes to provide strongly typed access to groups of related settings. For this, create a SmtpOptions Class with all the required properties.
public class SmtpOptions
{
public string Server { get; set; } = String.Empty;
public string Port { get; set; } = String.Empty;
public string FromAddress { get; set; } = String.Empty;
}
Add the SmtpOption to the service container with Configure and bound to configuration.
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SmtpOptions>(Configuration.GetSection("Smtp"));
}
Now read the value in the controller by injecting IOptions<SmtpOptions>
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
private readonly SmtpOptions _smtp;
public EmployeeController(IOptions<SmtpOptions> smtpOptions)
{
_smtp = smtpOptions.Value;
}
}
3. Read Array of Object using Option Pattern(Preferred Approach): We try to read here AppsettingGroup Regions from the appsettings.json
Create AppsettingGroupOptions class
namespace LearnWebAPI.OptionModels
{
public class AppsettingGroupOptions
{
public List<Region> Regions { get; set; }
}
public class Region
{ public int Id { get; set; }
public string Code { get; set; }
public string DisplayName { get; set; }
}
}
Add the AppsettingGroupOptions to the service container with Configure and bound to Configure.
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppsettingGroupOptions>(Configuration.GetSection("AppsettingGroup"));
}
Now read the value in the controller by injecting IOptions<AppsettingGroupOptions>
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
private readonly AppsettingGroupOptions _groupOptions;
public EmployeeController(IOptions<AppsettingGroupOptions> groupOptions)
{
_groupOptions = groupOptions.Value;
}
}
4. Read Array of Object using GetSection and GetChildren(Not Preferred Approach): We try to read here AppsettingGroup Regions from the appsettings.json.
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
public EmployeeController(IConfiguration configuration)
{
IConfigurationSection regionSection = configuration
.GetSection("AppsettingGroup:Regions");
var regionArray = regionSection.GetChildren();
var regionsValues = regionArray?.Select(configSection =>
{ return new Region()
{
Id= int.Parse(configSection["Id"]),
Code = configSection["Code"],
DisplayName = configSection["DisplayName"]
};
});
}
}
Below is the final code snippet with all the examples.
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
private readonly SmtpOptions _smtp;
private readonly AppsettingGroupOptions _groupOptions;
public EmployeeController(IConfiguration configuration,
IOptions<SmtpOptions> smtpOptions,
IOptions<AppsettingGroupOptions> groupOptions
)
{ // 1. Reading connection string
string connectionString = configuration.GetConnectionString("SQLConnection");
//2. Reading key;value pair using Key
string myValue = configuration["MyKey"];
//3. Reading Smtp object through IOptions
_smtp = smtpOptions.Value;
//4. Reading AppsettingGroup which contains the Region Arrays through Ioption
_groupOptions = groupOptions.Value;
//5. Reading AppsettingGroup using GetSection and GetChildren
IConfigurationSection regionSection = configuration
.GetSection("AppsettingGroup:Regions");
var regionArray = regionSection.GetChildren();
var regionsValues = regionArray?.Select(configSection =>
{
return new Region()
{
Id= int.Parse(configSection["Id"]),
Code = configSection["Code"],
DisplayName = configSection["DisplayName"]
};
});
}
}
Github commit ID for more details: https://github.com/rahulsdotnet/LearnWebAPI/commit/c906e8c915d23b1438cab377f2e063dc63a94fa1
Hope this article finds you well. Thanks for reading this.