C# tutorials > Frameworks and Libraries > ASP.NET Core > Configuration and Options (appsettings.json, environment variables)
Configuration and Options (appsettings.json, environment variables)
This tutorial explains how to manage configuration settings in ASP.NET Core applications using `appsettings.json` files and environment variables. ASP.NET Core's configuration system is flexible and powerful, allowing you to easily manage settings for different environments and deployment scenarios.
Introduction to Configuration in ASP.NET Core
ASP.NET Core utilizes a configuration system that prioritizes different configuration sources. These sources are typically layered, with later sources overriding earlier ones. Common sources include `appsettings.json`, `appsettings.{Environment}.json`, environment variables, command-line arguments, and user secrets (for development). This allows for a robust approach where defaults are in the JSON files, but can be overridden by environment-specific variables or command line parameters.
Using appsettings.json
`appsettings.json` is the primary configuration file in ASP.NET Core. It uses JSON format to define key-value pairs or hierarchical configurations. You can also create environment-specific configuration files like `appsettings.Development.json`, `appsettings.Production.json`, etc., which override the base `appsettings.json` settings when the corresponding environment is active.
Example appsettings.json
This example demonstrates a typical `appsettings.json` file. It defines logging configurations, allowed hosts, and a custom section called `MySettings` with two properties: `ApiUrl` (a string) and `Timeout` (an integer). These settings can be accessed in your application code.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MySettings": {
"ApiUrl": "https://example.com/api",
"Timeout": 30
}
}
Accessing Configuration Settings in Code
This code snippet demonstrates how to access configuration settings using the `IConfiguration` interface, which is injected into the class constructor. `GetSection("MySettings")` retrieves the `MySettings` section, and then you can access individual properties using the indexer (e.g., `["ApiUrl"]`). Alternatively, you can use `GetValue
using Microsoft.Extensions.Configuration;
public class MyService
{
private readonly string _apiUrl;
private readonly int _timeout;
public MyService(IConfiguration configuration)
{
_apiUrl = configuration.GetSection("MySettings")["ApiUrl"];
_timeout = configuration.GetValue<int>("MySettings:Timeout");
}
public void DoSomething()
{
Console.WriteLine($"API URL: {_apiUrl}, Timeout: {_timeout}");
}
}
Using Environment Variables
Environment variables are a crucial part of configuration, especially in production environments. They allow you to override settings without modifying the application code or configuration files. This is important for security (e.g., storing API keys) and environment-specific settings (e.g., database connection strings).
Setting Environment Variables
Environment variables can be set at the operating system level (e.g., using the `set` command in Windows or the `export` command in Linux) or through your deployment environment (e.g., Azure App Service, Docker containers, Kubernetes). The names are case-insensitive in many systems, but it's best to adhere to a consistent naming convention (e.g., uppercase with underscores). In ASP.NET Core, you can access environment variables using `System.Environment.GetEnvironmentVariable()` or, preferably, through the `IConfiguration` interface.
Environment Variable Overrides
Suppose you have the above in `appsettings.json`, and you set an environment variable named `MySettings:ApiUrl` to `https://production.example.com/api`. ASP.NET Core will use the value from the environment variable, effectively overriding the value in `appsettings.json`. This is because environment variables are usually loaded after `appsettings.json` and therefore have higher precedence.
{
"MySettings": {
"ApiUrl": "https://default.example.com/api"
}
}
Accessing Environment Variables Through IConfiguration
This code shows how to access environment variables directly through the `IConfiguration` interface using the string indexer. ASP.NET Core automatically integrates environment variables into the configuration system. Note that the path is the same as if you were retrieving this value from the `appsettings.json` file.
using Microsoft.Extensions.Configuration;
public class MyService
{
private readonly string _apiUrl;
public MyService(IConfiguration configuration)
{
_apiUrl = configuration["MySettings:ApiUrl"];
}
public void DoSomething()
{
Console.WriteLine($"API URL: {_apiUrl}");
}
}
ConfigurationBuilder
This demonstrates how to configure the configuration sources directly using `ConfigurationBuilder`. You can control the order in which the sources are added, effectively controlling their precedence. `AddJsonFile` loads JSON configuration files, and `AddEnvironmentVariables` loads environment variables. The `optional: true` parameter indicates that the file is not required to exist. `reloadOnChange: true` will automatically reload the configuration when the file is changed. The `CreateDefaultBuilder` method automatically adds several configuration sources, including `appsettings.json`, `appsettings.{Environment}.json`, environment variables, and command-line arguments. The code snippet clears default settings and then adds them back to have full control on precedence.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear(); // Remove all default configuration providers
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<Startup>();
});
}
Concepts behind the snippet
The key concept is *configuration layering*, where different sources provide configuration values, and later sources override earlier ones. This provides flexibility for different environments and deployment scenarios. Understanding `IConfiguration`, `appsettings.json`, and environment variables is crucial for building robust ASP.NET Core applications.
Real-Life Use Case Section
Consider an application that connects to a database. The database connection string should *never* be hardcoded into the application or stored in source control. Instead, it should be stored as an environment variable in the production environment. In development, you might use a local database with a different connection string, stored in `appsettings.Development.json`. The code uses the `IConfiguration` interface to retrieve the connection string, ensuring that the correct value is used depending on the environment.
Best Practices
Interview Tip
Be prepared to discuss the order of precedence of configuration sources in ASP.NET Core (e.g., command-line arguments > environment variables > `appsettings.{Environment}.json` > `appsettings.json`). Also, be able to explain how to use the `IConfiguration` interface and the different ways to access configuration values.
When to use them
Memory footprint
The memory footprint of the configuration system itself is relatively small. However, be mindful of the size of your `appsettings.json` files, especially if you have a large number of settings. The configuration is generally loaded into memory once at application startup. Caching frequently accessed values can also improve performance if you are dealing with computationally expensive configuration retrieval.
Alternatives
Pros
Cons
FAQ
-
How do I access configuration settings in a class that is not injected?
You can access the `IConfiguration` instance through the service provider, typically available from the `HttpContext` in web applications or by resolving it from the dependency injection container directly in non-web scenarios. However, it's generally better to inject the `IConfiguration` interface into the constructor of your classes whenever possible. -
How do I reload the configuration if I change appsettings.json at runtime?
Set `reloadOnChange: true` when adding the `appsettings.json` file to the configuration builder. This will automatically reload the configuration when the file changes. However, be aware that this might affect performance if the file is changed frequently. -
What if I need to store lists or complex objects in configuration?
You can serialize complex objects to JSON and store them as a string in `appsettings.json`. Then, you can deserialize the JSON string back into an object in your code. Alternatively, you can create custom configuration sections using strongly-typed configuration classes, which can be bound to the configuration data.