How to read ConnectionString from AppSettings.json

Install following package


// nuget package manager
dotnet add package Microsoft.Extensions.Configuration --version 7.0.0
 

Create a new class called"AppSettingHelper" and copy past following code.


// namespaces
namespace AppSettingHelper
{
    using Microsoft.Extensions.Configuration;
    using System.IO;
public class AppConfiguration { public readonly string _connectionString = string.Empty;
public AppConfiguration() { var configurationBuilder = new ConfigurationBuilder(); var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"); configurationBuilder.AddJsonFile(path, false);
var root = configurationBuilder.Build(); _connectionString = root.GetSection("ConnectionStrings").GetSection("DBConnectionString").Value; } public string ConnectionString { get => _connectionString; } } }

// appsettings.json 
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Log4Net": "Error"
    }
  },
  "ConnectionStrings": {
    "DBConnectionString": "Data Source=./;Initial Catalog=SOMEDB;Persist Security Info=True;TrustServerCertificate=True;User ID=sa;Password=password;MultipleActiveResultSets=True;App=EntityFramework;"
  },

Summary:

Easy step to read data from appsettings.json