Introduction
A distributed application must be able to run in different environments without changing its source code. During development, the application may use SQL Server, Redis, and RabbitMQ containers on a local machine. Tests may use isolated resources, while production may use managed services or a secured container platform. Hard-coding these differences inside microservices makes the system less portable and less secure.
In this lesson, we will examine ASP.NET Core configuration providers, environment names, environment variables, and .NET User Secrets. We will then define parameters in the Aspire AppHost and pass values to the Catalog and Order services. Real passwords will not be placed in the examples; sensitive values are represented as placeholders.
Understanding configuration sources and precedence
ASP.NET Core can read configuration from several sources. Common sources include appsettings.json, appsettings.{Environment}.json, User Secrets, environment variables, and command-line arguments. When the same key exists in multiple sources, the higher-priority source overrides the earlier value.
A practical convention is:
appsettings.json: Shared, non-sensitive defaults.appsettings.Development.json: Development-specific settings.appsettings.Test.json: Settings for automated or integration tests.- User Secrets: Passwords and tokens used during local development.
- Environment variables or a secret store: Container, CI/CD, and production values.
- Command-line arguments: Temporary overrides with the highest priority.
The environment name is commonly set with DOTNET_ENVIRONMENT or, for web applications, ASPNETCORE_ENVIRONMENT. When the application runs in the Development environment, appsettings.Development.json is loaded. Aspire also has an AppHost environment that can be controlled with ASPIRE_ENVIRONMENT. These are related but distinct concepts: the AppHost environment affects evaluation of the application model, while the child service environment is not changed automatically.
Application settings example
{
"Application": {
"Name": "Catalog",
"EnableDetailedErrors": false
},
"Cache": {
"DefaultTtlSeconds": 60
}
}In the Development file, only environment-specific and safe settings should be changed:
{
"Application": {
"EnableDetailedErrors": true
},
"Cache": {
"DefaultTtlSeconds": 300
}
}Reading these values through strongly typed options is safer than scattering string keys throughout the application:
public sealed class ApplicationOptions
{
public string Name { get; set; } = "";
public bool EnableDetailedErrors { get; set; }
}
builder.Services.Configure<ApplicationOptions>(
builder.Configuration.GetSection("Application"));Use IOptions<ApplicationOptions> for normal access, or IOptionsMonitor<ApplicationOptions> when changes must be observed. Treating the options class as a central contract makes configuration easier to validate and maintain.
Environment variables and hierarchical keys
Environment variables use a double underscore to represent configuration hierarchy. For example, the Cache:DefaultTtlSeconds key can be supplied as Cache__DefaultTtlSeconds on Linux, Windows, and in containers.
Cache__DefaultTtlSeconds=120
Application__EnableDetailedErrors=falseConnection strings conventionally belong under the ConnectionStrings section:
ConnectionStrings__CatalogDb=Server=sql;Database=Catalog;User Id=app;Password=...Environment variables can override the same keys from JSON files. This allows one container image to run in multiple environments. However, environment variables may be visible through operating-system or process inspection tools, so they should not automatically be treated as a complete production secret-management solution.
Using User Secrets for local development
User Secrets allow developers to store passwords and tokens outside the project directory and source code. These values must not be committed to Git. User Secrets are not an encrypted production vault; they are a local development convenience.
From the Catalog API project directory, run:
dotnet user-secrets init
dotnet user-secrets set "ConnectionStrings:CatalogDb" "Server=localhost;Database=Catalog;User Id=app;Password=local-only"
dotnet user-secrets set "ExternalServices:InventoryApiKey" "local-placeholder"When the application runs in the Development environment, the default configuration pipeline can read these values. Do not copy production passwords into User Secrets. Production values should come from a secure secret store or the hosting platform's secret mechanism.
Providing parameters through the Aspire AppHost
Aspire allows external values in the distributed application model to be represented as parameters. Parameters can model ordinary values, connection strings, or secrets. Sensitive values should be marked with secret: true.
var builder = DistributedApplication.CreateBuilder(args);
var sqlPassword = builder.AddParameter(
"sql-password",
secret: true);
var rabbitPassword = builder.AddParameter(
"rabbitmq-password",
secret: true);
var sql = builder.AddSqlServer(
"sql",
password: sqlPassword);
var catalogDb = sql.AddDatabase("catalogdb");
var messaging = builder.AddRabbitMQ(
"messaging",
password: rabbitPassword);
var catalog = builder.AddProject<Projects.CatalogApi>("catalog-api")
.WithReference(catalogDb)
.WithReference(messaging)
.WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development")
.WithEnvironment("Application__Name", "Catalog")
.WithEnvironment("Application__EnableDetailedErrors", "true");
builder.AddProject<Projects.OrderApi>("order-api")
.WithReference(messaging)
.WithEnvironment("ASPNETCORE_ENVIRONMENT", "Development")
.WithEnvironment("Application__Name", "Order");
builder.Build().Run();The SQL Server and RabbitMQ credentials are not written directly into the AppHost source code. The AddParameter calls declare that the values will be supplied externally. WithReference connects a service to a resource. Aspire can then expose resource connection information through configuration and environment values that the service can consume.
A parameter can also be passed directly as an environment variable:
var inventoryUrl = builder.AddParameter("inventory-base-url");
builder.AddProject<Projects.CatalogApi>("catalog-api")
.WithEnvironment("Inventory__BaseUrl", inventoryUrl);For a safe local value, the parameter can be configured in the AppHost's appsettings.json:
{
"Parameters": {
"inventory-base-url": "https://localhost:7003"
}
}For secret parameters, User Secrets are a better local source:
dotnet user-secrets init
dotnet user-secrets set "Parameters:sql-password" "local-development-only"
dotnet user-secrets set "Parameters:rabbitmq-password" "local-development-only"The AppHost can read a configured value, or request the value when the application is run or published. In CI/CD, parameters are commonly supplied by the pipeline's secret mechanism using environment variable names such as Parameters__sql-password.
Separating environments deliberately
Development, Test, and Production are not merely different labels. They represent different security and operational rules.
| Environment | Typical source | Recommended behavior |
|---|---|---|
| Development | Local containers, User Secrets | Detailed logs, local resources, fast feedback |
| Test | Isolated database and queue | Deterministic data and short-lived resources |
| Production | Secret store and managed services | Least privilege, limited error details, controlled access |
For example, production should not expose detailed exception messages to clients. EnableDetailedErrors should remain false, while full details are sent to logs and tracing systems. Development and production connection strings should also use separate secret names and separate credentials.
Diagnosing configuration failures
In distributed systems, “it does not work” often means that the wrong environment or an expected key is missing. Use this sequence:
- Check the service environment with
builder.Environment.EnvironmentName. - Check whether the expected key exists, but never log the secret value itself.
- Verify that the connection string name matches the resource name and the
ConnectionStringskey. - Confirm that the AppHost parameter is declared with the expected name and passed to the child resource.
- Inspect container environment names such as
Cache__DefaultTtlSeconds. - Use the Aspire dashboard to inspect resource state, logs, and environment metadata.
Required configuration should be validated during startup:
builder.Services.AddOptions<ApplicationOptions>()
.Bind(builder.Configuration.GetSection("Application"))
.Validate(options => !string.IsNullOrWhiteSpace(options.Name),
"Application:Name is required")
.ValidateOnStart();For diagnosis, log only whether a value is present:
var hasCatalogConnection =
!string.IsNullOrWhiteSpace(
builder.Configuration.GetConnectionString("CatalogDb"));
logger.LogInformation(
"Catalog database configuration present: {Present}",
hasCatalogConnection);Never log passwords, API keys, or tokens. Also avoid putting secret values into exception messages, telemetry attributes, or request headers that are recorded by diagnostic middleware.
Common mistakes
- Putting secrets in appsettings.json: The file may be committed to Git or included in a container image.
- Assuming the AppHost environment flows automatically: Set
ASPNETCORE_ENVIRONMENTorDOTNET_ENVIRONMENTexplicitly for child services. - Using one connection string in every environment: Separate resources and credentials by environment.
- Using one underscore for hierarchy: Use
__for hierarchical environment variable keys. - Declaring a secret as a normal parameter: Use
secret: truefor sensitive parameter values. - Hiding startup configuration failures: Validate required options, but never include secret values in validation errors.
- Running Production as Development: Detailed errors and relaxed security settings can leak outside the local machine.
Short practice exercise
Complete the following exercise for the Catalog API:
- Add
Name,EnableDetailedErrors, andRegiontoApplicationOptions. - Create
appsettings.json,appsettings.Development.json, andappsettings.Test.json. - Declare an AppHost parameter named
catalog-regionand pass it asApplication__Region. - Enable
ValidateOnStartforApplicationOptions. - Write only the environment name and region to the startup log; never write a connection string or secret.
- Set the parameter first with User Secrets and then with an environment variable to observe precedence.
Conclusion
Configuration management determines not only how a microservice runs, but also where it runs and which security rules apply. ASP.NET Core configuration providers handle common settings and environment overrides, while User Secrets provide a useful local boundary for development. The Aspire AppHost brings resources, parameters, and service environments together in one application model.
The goal is to run the same code in Development, Test, and Production without embedding environment-specific secrets in the application. To achieve that goal, keep secrets out of source control, declare AppHost parameters explicitly, configure child service environments deliberately, and validate required settings during startup.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?azure-portal=true&view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/external-parameters
- https://learn.microsoft.com/en-us/dotnet/aspire/app-host/configuration
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings/