In modern .NET Core and ASP.NET Core applications, configuration management is a critical aspect of scalable and maintainable application design. The preferred approach for managing configuration is using the appsettings.json file. This file, along with other configuration providers like environment variables and command-line arguments, forms the foundation for dynamic and environment-specific configurations.
The appsettings.json file is a JSON-based configuration file introduced in .NET Core. It is widely used for storing application settings like connection strings, logging configurations, API keys, and other key-value settings.
{
"AppSettings": {
"ApplicationName": "MyDotNetApp",
"Version": "1.0.0"
},
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=AppDB;Trusted_Connection=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
By default, ASP.NET Core loads the appsettings.json file during application startup using the CreateDefaultBuilder() method in Program.cs.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
The CreateDefaultBuilder method includes:
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
var appName = _configuration["AppSettings:ApplicationName"];
ViewBag.AppName = appName;
return View();
}
}
public class AppSettings
{
public string ApplicationName { get; set; }
public string Version { get; set; }
}
Register in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Inject and use in controller:
public class HomeController : Controller
{
private readonly AppSettings _settings;
public HomeController(IOptions<AppSettings> settings)
{
_settings = settings.Value;
}
public IActionResult Index()
{
ViewBag.AppName = _settings.ApplicationName;
return View();
}
}
You can create separate files like appsettings.Development.json or appsettings.Production.json. ASP.NET Core automatically loads the appropriate file based on the environment.
set ASPNETCORE_ENVIRONMENT=Development
export ASPNETCORE_ENVIRONMENT=Development
{
"AppSettings": {
"ApplicationName": "MyApp (Development)",
"Version": "1.0.0-dev"
}
}
You can reload configurations automatically without restarting the application by enabling reloadOnChange.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
JSON supports nesting and arrays. For example:
{
"AppSettings": {
"SupportedCultures": [ "en-US", "fr-FR", "es-ES" ]
}
}
Access it via:
var culture = _configuration["AppSettings:SupportedCultures:0"];
In non-web .NET Core apps like worker services, you still use Host.CreateDefaultBuilder.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
var config = hostContext.Configuration;
string appName = config["AppSettings:ApplicationName"];
});
Avoid putting secrets in appsettings.json. Use environment variables or user secrets (for development).
dotnet user-secrets init
dotnet user-secrets set "AppSettings:ApiKey" "your-secret-key"
set AppSettings__ApiKey=your-secret-key
Use double underscore to represent nested keys.
The default hierarchy is:
Later sources override earlier ones.
You can inject IConfiguration anywhere in your application:
public class EmailService
{
private readonly string _fromEmail;
public EmailService(IConfiguration configuration)
{
_fromEmail = configuration["EmailSettings:From"];
}
}If a value is not found:
var setting = _configuration["MissingKey"]; // returns null
JSON must be properly formatted (commas, braces, etc.). Use a JSON validator if needed.
// appsettings.json
{
"EmailSettings": {
"From": "admin@example.com",
"Host": "smtp.example.com",
"Port": 587
}
}
public class EmailSettings
{
public string From { get; set; }
public string Host { get; set; }
public int Port { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
}
Configuration management using appsettings.json in .NET Core provides a robust, flexible, and environment-friendly way to manage application settings. Whether you're developing ASP.NET Core applications, console apps, or background services, proper configuration practices help you write scalable and secure code.
By leveraging strongly-typed settings, environment-specific files, and secure storage options, you ensure that your applications are adaptable and maintainable across different environments.
Copyrights © 2024 letsupdateskills All rights reserved