How to Get Connection String from Appsettings.json? .net Core Console Application

Easy Steps

  1. Add appSettings.json
  2. Install nuget: Microsoft.Extensions.Configuration(include FileExtensions and Json)
  3. Use the ‘ConfigurationBuilder’ to build key/value based configuration settings for use in the application

1. Add an AppSettings.json File

Right-click on the project and select ‘Add New Item’. In the search box type ‘json’ keyword and select ‘JavaScript JSON Configuration File’. Rename jsconfig1.json to the ‘appSettings.json’.

add appSettings.json in Console Application

The ‘appSettings.json’ content:

appSEttings ConnectionStrings section

2. Install Microsoft.Extensions.Configuration Libraries

The next libraries required to read configuration from the appSettings.json file:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

Use ‘Manage NuGet Packages…’ menu option and find Microsoft.Extensions.Configuration libraries.

Run Manage Packages for Solution


Microsoft.Extensions.Configuration libraries

3. Read Connection string using ConfigurationBuilder and IConfiguration

By using ConfigurationBuilder, you can store configuration values in a JSON file, for example, and then retrieve them at run time. The Build method creates IConfiguration with keys and values from the appSettings.json. And using the extension method GetConnectionString you retrieve the value of your connection string. And do not forget to set ‘Copy to Output Directory’ to ‘Copy always’ otherwise appSettings.json won’t be found.

Read Connection Strings from AppSettings.json


Connection string read

C# code

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace AppJsonConnectionString
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var builder = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
            IConfiguration _configuration = builder.Build();
            var myConnectionString1 = _configuration.GetConnectionString("MyConnectionString1");
            Console.WriteLine(myConnectionString1);
        }
    }
}

 

Leave a Reply

Your email address will not be published.