How to get values from appsettings.json in a console application using .NET Core?

Your example is mixing in some ASP NET Core approaches that expect your code to be hosted. To minimally solve the issue of getting options or settings from a JSON configuration, consider the following:

A config.json file, set to “Copy to Output Directory” so that it is included with the build:

{
  "MyFirstClass": {
    "Option1": "some string value",
    "Option2": 42
  },
  "MySecondClass": {
    "SettingOne": "some string value",
    "SettingTwo": 42
  }
}

The following approach will load the content from the JSON file, then bind the content to two strongly-typed options/settings classes, which can be a lot cleaner than going value-by-value:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json

namespace SampleConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config.json", optional: false);

            IConfiguration config = builder.Build();

            var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
            var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
            Console.WriteLine($"The answer is always {myFirstClass.Option2}");
        }
    }

    public class MyFirstClass
    {
        public string Option1 { get; set; }
        public int Option2 { get; set; }
    }

    public class MySecondClass
    {
        public string SettingOne { get; set; }
        public int SettingTwo { get; set; }
    }
}

Leave a Comment