ASP.NET Core Configuration: appsettings.json, Environment Variables, and Options
ASP.NET Core applications commonly need settings such as connection strings, API URLs, feature flags, and logging options. The built-in configuration system provides a consistent way to load and consume those values.
đ appsettings.json
A simple configuration file can contain application settings:
{
"AppSettings": {
"ApplicationName": "MyApp",
"TimeoutSeconds": 30
}
}
ASP.NET Core loads appsettings.json automatically in the standard application setup.
đ Environment-Specific Settings
You can provide environment-specific configuration with files such as appsettings.Development.json and appsettings.Production.json. This allows development and production settings to remain separate.
đ Environment Variables
Sensitive or deployment-specific values can be supplied through environment variables instead of being committed to source control.
var connectionString =
builder.Configuration.GetConnectionString("DefaultConnection");
For nested configuration values, environment-variable providers support hierarchical keys.
⥠Reading Configuration Directly
var appName = builder.Configuration["AppSettings:ApplicationName"];
var timeout = builder.Configuration.GetValue<int>(
"AppSettings:TimeoutSeconds");
This is convenient for a small number of values, but larger groups of related settings are usually easier to manage with the Options pattern.
đ§Š Strongly Typed Options
public class AppSettings
{
public string ApplicationName { get; set; } = "";
public int TimeoutSeconds { get; set; }
}
builder.Services.Configure<AppSettings>(
builder.Configuration.GetSection("AppSettings"));
A service can then consume the settings through IOptions<AppSettings>.
đĢ Don't Store Secrets in Source Control
Passwords, production connection strings, API keys, and other secrets should not normally be committed to a public repository. Use environment variables, a secret store, or your hosting platform's secret configuration.
đ§ Key Takeaway
ASP.NET Core configuration is layered and flexible. Use simple configuration access for occasional values and strongly typed options when a feature has several related settings.
Continue with ⥠ASP.NET Core Tutorials.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.