How to manage SQL Database Connection string in .Net Core?


A database connection string is a very basic task for a developer who is working on ASP.Net. But defining a database connection string in .Net Core and reading back into C# code is a little different than the traditional ASP.Net framework.
The asp.net Core is a new open-source framework introduced by Microsoft.
ASP.Net Core is a cross-platform open-source framework for building modern applications including cloud-based development.

In ASP.Net framework, we had web.config file to manage all the configurable things including the database connection string.

But in .Net core, we don't have web.config. In ASP.Net Core we have JSON based file to manage database connection string. Because application developed in ASP.Net Core is platform-dependent and JSON is readable to all platforms.

To know how to create a web application in ASP.Net Core, follow this blog - How to create a web application in ASP.Net Core?

In .Net Core web application, we have "appsettings.json" file to write a database connection string. 

By default, appsettings.json file contains below code -

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Add below line in appsettings.json file 

"ConnectionStrings": {
    "DefaultConnection": "Data Source=127.0.0.1;Initial Catalog=MySQLDB;Persist Security Info=True;User ID=sa;Password=12345"
  }

After adding Connection string, complete appsettings.json file looks like below -

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=127.0.0.1;Initial Catalog=MySQLDB;Persist Security Info=True;User ID=sa;Password=12345"
  },
  "AllowedHosts": "*"
}

Once we have done with a connection string, now we will try to read this connection string in C# code.

Write below code in C# to read apsettings.json file -

var dbconfig = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();

And then read the ConnectionString from the variable dbconfig.

if (!string.IsNullOrEmpty(dbconfig.ToString()))
                {
                    string dbconnectionStr = dbconfig["ConnectionStrings:DefaultConnection"];
                }

I hope you like this blog.
Please share this blog on social media and write your comment below.

Previous Blog - ASP.Net Core Razor Pages handler methods
Next Blog - ASP.Net Core CRUD example using ADO.Net


Comments

Popular