ASP.NET Core Interview Question #43

How are connection strings stored and read in ASP.NET Core?

Application Structure & Configuration Junior Beginner

Quick Interview Answer

Connection strings are commonly placed in the ConnectionStrings section of configuration. They can then be retrieved using IConfiguration.GetConnectionString(name).

Detailed Explanation

Connection strings are commonly placed in the ConnectionStrings section of configuration. They can then be retrieved using IConfiguration.GetConnectionString(name).

For Entity Framework Core, the retrieved connection string is normally passed to the database provider when registering the DbContext.

Production credentials should be supplied through secure configuration mechanisms. The configuration system can override a connection string from appsettings.json with an environment variable or another higher-priority provider.

Code Example

// appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=AppDb;Trusted_Connection=True;"
  }
}

// Program.cs
var cs = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(cs));