This ASP.NET blog post will guide you through the steps of differentiating settings per environment in ASP.NET Core and provide a simple how to example.
ASP.NET Core uses a configuration system that is highly flexible and based on key-value pairs. Configuration settings can be stored in various formats, such as JSON files, environment variables, command-line arguments, etc. The framework automatically loads configurations from multiple sources and merges them together in a specific order.
Configuration Sources and Their Order
Below is the order in which configurations are loaded by default in an ASP.NET Core application:
appsettings.json
appsettings.{Environment}.json
(e.g.,appsettings.Development.json
,appsettings.Production.json
)- Environment-specific variables
- Command-line arguments
This order ensures that environment-specific settings can override settings in the general appsettings.json
based on the current environment.
Differentiating Settings Per Environment
In the following example, We will configure two environments, Development and Production, using JSON files.
Create a base configuration file named appsettings.json
and environment-specific configuration files like appsettings.Development.json and appsettings.Production.json. Here’s an example setup:
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"ConnectionStrings": {
"MyApp": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
}
}
appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug"
}
},
"ConnectionStrings": {
"MyApp": "Server=localhost;Database=devDB;Integrated Security=True;"
}
}
appsettings.Production.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MyApp": "Server=prodServer;Database=prodDB;User Id=prodUser;Password=prodPassword;"
}
}
The file structure should look like:
Activate Environment
Once the environment files are set, we can activate an environment using Environment Variables. In the example below, I will activate the Production environment
$Env:DOTNET_ENVIRONMENT = "Production"
Once the environment is set, we can run the application
dotnet run
Just a few things to note: When running an ASP.NET in Production mode, the terminal will not show any output and will only display the output below, which doesn’t give much information about the runtime.
Building…
You might need to restart your terminal when switching between environments because Windows caches the environment variables.
Leave a Reply