How to get ConnectionString from appsettings.json


1 Answers

Install following package

dotnet add package Microsoft.Extensions.Configuration --version 7.0.0

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

 

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

.....




Your answer

Cancel