Keywords: ASP.NET Core 6 | appsettings.json | Configuration Access | Strongly-Typed Binding | Dependency Injection
Abstract: This article provides a comprehensive guide on accessing appsettings.json configuration in ASP.NET Core 6's Program.cs file. It covers both direct configuration value access and strongly-typed configuration binding methods, with practical code examples demonstrating how to replace hard-coded connection strings and detailed analysis of the configuration system's underlying mechanisms.
Configuration Access Fundamentals
In ASP.NET Core 6, while the traditional Startup class has been consolidated into the Program.cs file, the core functionality of the configuration system remains intact. The WebApplication.CreateBuilder(args) method automatically loads the appsettings.json file and stores its configuration information in the builder.Configuration property.
Direct Configuration Value Access
For simple configuration values, direct access via configuration keys is available. For example, define a Redis connection string in appsettings.json:
{
"Redis": "localhost:6379"
}
In Program.cs, access it as follows:
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["Redis"];
});
Strongly-Typed Configuration Binding
For complex configuration structures, strongly-typed binding is recommended. First, define the corresponding configuration class:
public class Settings
{
public string Url { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Define the corresponding configuration section in appsettings.json:
{
"Settings": {
"Url": "myurl",
"Username": "guest",
"Password": "guest"
}
}
Perform configuration binding in Program.cs:
var settings = builder.Configuration.GetSection("Settings").Get<Settings>();
var url = settings.Url;
In-Depth Configuration System Analysis
The ASP.NET Core configuration system supports multiple configuration sources, including JSON files, environment variables, and command-line arguments. The system merges these sources in a specific priority order, with later-loaded configurations overriding earlier ones.
Dependency Injection Integration
Configuration objects can be used throughout the application via the dependency injection container. For example, register a configuration section as a singleton service:
builder.Services.Configure<Settings>(builder.Configuration.GetSection("Settings"));
Then inject and use it in controllers or other services via IOptions<Settings>.
Best Practice Recommendations
In real-world projects, follow these best practices: use strongly-typed configuration classes for type safety; create different appsettings files for different environments (development, testing, production); store sensitive information in environment variables or key management services; organize configuration structures reasonably to avoid excessive nesting.