How to read values from appsettings.json in C# .NET Core 6/7/8?

How to read values from appsettings.json in C# .NET 6/7/8 for a console app or you need to read it inside asp.net core which does not have dependency injection such as Entity Framework Core DBContext there? Either console app or asp.net core DBContext you can read it using Microsoft.Extensions.Configuration.

First, if you don’t have an existing app, you can create a new console application using this command > dotnet new console.

Then, you need to add two nuget packages as below:

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json

Add an appsettings.json to read the value from:

{
    "AppSettings": {
      "Title": "My Console App",
      "Version": "1.0.0"
    },
    "ConnectionStrings": {
        "MySql": "server=localhost; database=dotnet; user=test; password=test",
        "SqlServer": "Data Source=localhost; Initial Catalog=dotnet; User Id=test; Password=test"
    }
}

To copy appsettings.json to debug/release folder, edit the .csproj and add the line below to ItemGroup:

    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>

Inside Program.cs, add the code below. Please note, it has few ways to read the values, the example below demonstrates three ways only.

using Microsoft.Extensions.Configuration;

var configuration = new ConfigurationBuilder()
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json")
    .Build();

// Method 1: Get directly
Console.WriteLine(configuration["AppSettings:Title"]);

// Method 2: Get via GetSection method.
var appSettings = configuration.GetSection("AppSettings");
Console.WriteLine(appSettings["Version"]);

// Method 3: Get via GetConnection method for connection string
var mysqlConnString = configuration.GetConnectionString("MySql");
Console.WriteLine($"MySQL Connection String: {mysqlConnString}");

Lastly, run dotnet run, the result will be like below:

$ dotnet run
My Console App
1.0.0
MySQL Connection String: server=localhost; database=dotnet; user=test; password=test

Github repo:
https://github.com/sanme98/dotnet-read-appsettings

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.