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; }
    }
}

I had the same issue with .NET Core and I found this solution to be working well:

  1. I have this appsettings.json
    {
      "App": 
      {
        "LoginCredentials": 
        {
           "ClientId": "xxx",
           "ClientSecret": "xxx",
           "TenantId": "xxx"
        },
        "DataBase": 
        {
            "PathToDatabases": "xxx"
        },
        "General": 
        {
           "PathToLogFiles": "xxx"
        }
      }

    }
  1. I created a class AppSettingsHandler.cs
    public class AppSettingsHandler
    {
        private string _filename;
        private AppSettings _config;

        public AppSettingsHandler(string filename)
        {
            _filename = filename;
            _config = GetAppSettings();
        }

        public AppSettings GetAppSettings()
        {
            var config = new ConfigurationBuilder()
               .SetBasePath(AppContext.BaseDirectory)
               .AddJsonFile(_filename, false, true)
               .Build();

            return config.GetSection("App").Get<AppSettings>();
        }
    }

  1. Then you need a "model" class for AppSettings:
    public class AppSettings
    {
        public LoginCredentialsConfiguration LoginCredentials { get; set; }
        public DatabaseConfiguration DataBase { get; set; }
        public GeneralConfiguration General { get; set; }
    }

and a model class for each of the included sub-classes, I only exemplify one here:

    public class LoginCredentialsConfiguration
    {
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string TenantId { get; set; }
    }
  1. In your Program.cs class, you can now get the parameters from the appsettings.json like this:
            var aH = new AppSettingsHandler("appsettings.json");
            var aS = aH.GetAppSettings();
            var myPath = aS.DataBase.PathToDatabases;

Of course you can tweak that code so that it will match your requirements, i. e., you have to define your own classes and subclasses and of course you can extend the AppSettingsHandler.cs by also getting other sections of the appsettings.json.


http://www.techtutorhub.com/article/how-to-read-appsettings-json-configuration-file-in-dot-net-core-console-application/83

helpfull !

  1. appsettings.json (after add appsettings.json, go to property and mark the file as copy to out directory)
{
  "ConnectionString": "Server=localhost;Database=tempDB;Uid=<dbUserName>;Pwd=<dbPassword>",
  "Smtp": {
    "Host": "smtp.gmail.com",
    "Port": "587",
    "Username": "<YourGmailUserName>",
    "Password": "<YourGmailPassword>",
    "From": "Your Name"
  }
}

2.package needed

dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json
  1. program.cs
using System; 
using Microsoft.Extensions.Configuration;

    class Program
        {
            static void Main(string[] args)
            {
                  var builder = new ConfigurationBuilder()
                   .AddJsonFile($"appsettings.json", true, true);
    
                var config = builder.Build();
                var connectionString = config["ConnectionString"];
                var emailHost = config["Smtp:Host"];
                Console.WriteLine($"Connection String is: {connectionString}");
                Console.WriteLine($"Email Host is: {emailHost}");
                Console.ReadLine();
            }
        }