Configuration in ASP.NET Core
Configuration is a fundamental aspect of any application, allowing you to manage settings that vary between environments (development, staging, production) or deployments. ASP.NET Core provides a flexible and extensible configuration system that supports various sources, including JSON files, environment variables, command-line arguments, and more.
Tip: The configuration system is designed to be highly composable. You can chain multiple configuration providers to create a layered configuration where settings from one provider can override settings from another.
Configuration Providers
ASP.NET Core uses configuration providers to read data from different sources. The default template includes providers for:
appsettings.json
files (and environment-specific versions likeappsettings.Development.json
)- Environment variables
- Command-line arguments
JSON Configuration
By default, ASP.NET Core loads configuration from appsettings.json
. You can also include environment-specific configuration files. For example, appsettings.Development.json
will be loaded when the application runs in the Development environment.
Here's an example of an appsettings.json
file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MyCustomSetting": {
"Key": "Value",
"Number": 123
}
}
Environment Variables
Environment variables are a common way to configure applications, especially in containerized or cloud environments. ASP.NET Core maps environment variables to configuration keys. By default, it uses a colon (:
) as a separator. For example, an environment variable named MyCustomSetting:Key
would override the Key
setting in appsettings.json
.
Command-line Arguments
You can also pass configuration settings directly on the command line. This is useful for quick overrides during development or for specific deployment scenarios. The format is similar to environment variables, using colons as separators.
dotnet run --MyCustomSetting:Key="CommandLineValue"
Accessing Configuration
The primary way to access configuration in ASP.NET Core is through the IConfiguration
interface. This interface is typically injected into your application's services, controllers, or Razor Pages.
Using IConfiguration
in Startup
The CreateHostBuilder
method in your Program.cs
file is where the configuration is set up. You can access it there:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
Using IConfiguration
in Controllers/Services
Inject IConfiguration
into your components:
public class MyController : Controller
{
private readonly IConfiguration _configuration;
public MyController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
var mySetting = _configuration["MyCustomSetting:Key"];
var myNumber = _configuration.GetValue("MyCustomSetting:Number");
ViewData["Message"] = $"My Custom Key: {mySetting}, My Number: {myNumber}";
return View();
}
}
Note: When accessing values, IConfiguration.GetValue<T>(key)
is preferred for strongly-typed retrieval, as it handles type conversion and provides a default value if the key is not found.
Options Pattern
For more complex configuration scenarios, the Options pattern is highly recommended. It allows you to bind configuration values to strongly-typed .NET objects.
- Define a class to hold your configuration values.
- Register this class with the Dependency Injection container, binding it to a configuration section.
- Inject the strongly-typed options class into your components.
Example:
1. Define the options class:
public class MyCustomSettings
{
public string Key { get; set; }
public int Number { get; set; }
}
2. Configure services in Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<MyCustomSettings>(Configuration.GetSection("MyCustomSetting"));
}
3. Inject and use in a controller:
using Microsoft.Extensions.Options;
public class MyController : Controller
{
private readonly MyCustomSettings _settings;
public MyController(IOptions<MyCustomSettings> options)
{
_settings = options.Value;
}
public IActionResult Index()
{
ViewData["Message"] = $"Options Key: {_settings.Key}, Options Number: {_settings.Number}";
return View();
}
}
Reloading Configuration
For configuration files like appsettings.json
, you can enable automatic reloading when the file changes. This is configured when adding the JSON provider:
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
When reloadOnChange
is set to true
, the application will monitor the specified file and reload the configuration automatically. For the Options pattern, you can inject IOptionsMonitor<T>
to get notifications about configuration changes.
Advanced Scenarios
- Secret Manager: For managing secrets during development.
- Key Vault: For securely storing and accessing secrets in production.
- Custom Providers: You can create your own configuration providers for custom data sources.
Explore these advanced topics to secure and manage your application's configuration effectively.