How to read configuration from appsettings.json in C#
By FoxLearn 3/6/2025 4:01:58 AM 28
Using the Microsoft.Extensions.Configuration
library, you can easily add configuration settings to any project.
In this guide, I’ll walk you through how to read configuration settings from appsettings.json in both a console application and in ASP.NET Core.
Read config from appsettings.json in a Console App
In this section, we'll go through the process of reading configuration values from appsettings.json in a console application.
Step 1: Add the appsettings.json File
The appsettings.json
file is simply a JSON file, so to add it to your project:
Create a new file named appsettings.json
and leave it empty at first:
{ }
Ensure that the appsettings.json
file is copied to the output directory. This can be done either in the project UI or within the .csproj
file:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
Step 2: Install Configuration Packages
To work with appsettings.json
, you need to install the following NuGet packages:
Install-Package Microsoft.Extensions.Configuration.Json Install-Package Microsoft.Extensions.Configuration.Binder
(Note: You can install these via the Package Manager Console under Tools > NuGet Package Manager > Package Manager Console.)
Step 3: Create a Custom Config Class
Add a class to represent your configuration settings.
For example, let’s define a DatabaseConfig
class to hold settings related to database connections:
public class DatabaseConfig { public string ConnectionString { get; set; } public int MaxConnections { get; set; } public bool IsEncrypted { get; set; } }
Step 4: Add Values to appsettings.json
Now, add a section to your appsettings.json
file with the values corresponding to your DatabaseConfig
class:
{ "DatabaseConfig": { "ConnectionString": "Server=localhost;Database=SampleDB;User Id=admin;Password=secret;", "MaxConnections": 50, "IsEncrypted": true } }
Step 5: Read the Config Section from appsettings.json
To read this configuration into your application:
- Use the
ConfigurationBuilder
to load theappsettings.json
file. - Use the
GetSection()
method to get the specific section. - Deserialize the JSON into your
DatabaseConfig
object withGet<T>()
.
For example:
using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .Build(); var section = config.GetSection("DatabaseConfig"); var databaseConfig = section.Get<DatabaseConfig>(); Console.WriteLine(databaseConfig.ConnectionString); Console.WriteLine(databaseConfig.MaxConnections); Console.WriteLine(databaseConfig.IsEncrypted);
When you run this, it will output the values from the DatabaseConfig
section in appsettings.json
:
Server=localhost;Database=SampleDB;User Id=admin;Password=secret; 50 True
Read config from appsettings.json in ASP.NET Core
ASP.NET Core abstracts much of the configuration reading for you, so most of the time, you’ll just need to decide how to load the configuration values.
For example, appsettings.json
for ASP.NET Core:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "DatabaseConfig": { "ConnectionString": "Server=localhost;Database=SampleDB;User Id=admin;Password=secret;", "MaxConnections": 50, "IsEncrypted": true } }
Option 1 - Use a Custom Config Class
This method involves loading the section into a custom configuration class. You then register the configuration class as a service and inject it wherever needed.
1. Define your custom config class (as shown earlier).
2. Read the section and register the class in Program.cs
:
using Microsoft.Extensions.Configuration; var builder = WebApplication.CreateBuilder(args); // Register services builder.Services.AddControllers(); // Load configuration section into a custom class builder.Services.Configure<DatabaseConfig>(builder.Configuration.GetSection("DatabaseConfig")); var app = builder.Build();
3. Inject the configuration in your controller:
[ApiController] [Route("[controller]")] public class ExampleController : ControllerBase { private readonly DatabaseConfig _config; public ExampleController(IOptions<DatabaseConfig> config) { _config = config.Value; } [HttpGet] public IActionResult GetConnectionDetails() { return Ok(_config.ConnectionString); } }
Option 2 - Use the Options Pattern
The options pattern works well when you need more features, such as validation or configuration reloading. The concept is similar to Option 1 but uses IOptions<T>
for more advanced features.
builder.Services.Configure<DatabaseConfig>(builder.Configuration.GetSection("DatabaseConfig"));
Then inject IOptions<DatabaseConfig>
into your controllers:
public class ExampleController : ControllerBase { private readonly IOptions<DatabaseConfig> _config; public ExampleController(IOptions<DatabaseConfig> config) { _config = config; } [HttpGet] public IActionResult GetMaxConnections() { return Ok(_config.Value.MaxConnections); } }
Option 3 - Use IConfiguration Directly
If you prefer not to create a custom class, you can inject IConfiguration
directly into your controller and access specific values:
public class ExampleController : ControllerBase { private readonly IConfiguration _config; public ExampleController(IConfiguration config) { _config = config; } [HttpGet] public IActionResult GetIsEncrypted() { var isEncrypted = _config.GetValue<bool>("DatabaseConfig:IsEncrypted"); return Ok(isEncrypted); } }
Accessing a Single Value from appsettings.json
Get a Value from a Section
If you want to read just one property from a section, such as DatabaseConfig:IsEncrypted
, you can do so with:
var isEncrypted = config.GetValue<bool>("DatabaseConfig:IsEncrypted");
Alternatively, use GetSection
with GetValue
:
var isEncrypted = config.GetSection("DatabaseConfig").GetValue<bool>("IsEncrypted");
Get a Top-Level Value
To read a simple value like AllowedHosts
, you can do so directly:
var allowedHosts = config.GetValue<string>("AllowedHosts");
In this guide, we've explored how to use appsettings.json
for reading configuration in both console applications and ASP.NET Core, along with different methods like custom config classes, the options pattern, and using IConfiguration
directly.
- How to Get Status Codes with HttpClient in C#
- How to use TimeZoneInfo in C#
- How to Get key with the max value in a dictionary in C#
- How to Get and send JSON with HttpClient in C#
- How to Deserialize JSON as a stream in C#
- How to use JsonNode in C#
- TimeZoneInfo with current UTC offset in C#
- How to Parser a CSV file in C#