How to get ConnectionString from appsettings.json in ASP.NET Core

By FoxLearn 2/18/2024 9:31:28 AM   345
This post shows you how to get a connection string from appsettings.json in ASP.NET Core

You can easily find your connection string add in appsettings.json file.

"ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=dbtest;User Id=sa;Password=123@qaz;Connection Timeout=3000;"
}

Creating a AppDbConnection class

public class AppDbConnection
{
    public string DefaultConnectionString { get; set; }
}

Opening your Startup class, then add a configuration as shown below.

services.Configure<AppDbConnection>(options =>
{
   options.DefaultConnectionString = Configuration.GetConnectionString("DefaultConnection");
});

You can get connection string from your repository as shown below.

private readonly string _connectionString;
public DataRepository(IOptions<AppDbConnection> config)
{
   _connectionString = config.Value.DefaultConnectionString;
}