.Net Core: Read Connection String from AppSettings.json file

Introduction

In this article I will explain different ways to store and read connection strings in appsettings.json with example In .Net Core and ASP.Net MVC Core. Microsoft has replaced System.Configuration class with IConfiguration interface in .Net Core.

Step 1 :

First, Need to Open AppSettings.json file from your project as mentioned below image.

.Net Core Read Connection String from AppSettings.json file

 

Step 2 :

After opening the AppSettings.json file, can you add ConnectionString in mentioned section as below code snippet .

Appsettting.json :

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MySqlCon": "server=MyPersionalPC;database=MyCoredb;Trusted_Connection=true;"
  }
}

Step 3 :

Now the best and dynamic way to access these ConnectionString, we need to configure IConfiguration  interface in Startup.cs file, after configuring interface we can get connection string in any class in entire project.

Startup.cs

    public class Startup
    {
        private IConfiguration Configuration { get; }
        public static string connectionstring { get; private set; }
        public Startup(IConfiguration _configuration)
        {       Configuration = _configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            string conString = this.Configuration.GetConnectionString("MySqlCon");
            connectionstring = conString;

            services.AddRazorPages();
        }

    }

Step 4:

Now you can access connection string dynamically any class of entire project, For example i have create one class named EmployeeService.cs  and getting connection as mentioned below code snippets.

Add Namespace : using Microsoft.Extensions.Configuration;

   
    public class EmployeeService
    {
        SqlConnection con = new SqlConnection(Startup.connectionstring);
        public void InsertEmployee()
        {

        }
    }

Summary :

Storing connection strings in AppSettings.json makes it easy way to change settings in production environment without touching the codebase or re-compiling. Once you learn about configuration in .NET Core and what methods to use it is quite easy to work with

Also Learn Relative Tutorial :

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *