Introduction
An application that works on a developer's machine is not automatically ready for production. Real-world systems must manage database connections, JWT signing keys, external service URLs, log levels, and environment-specific behavior in a secure and maintainable way. In this lesson, we will prepare our Clean Architecture ASP.NET Core Web API for production use.
Our goals are to configure the application by environment, keep sensitive values outside the source code, and produce meaningful structured logs. We will also add health checks, review safe error handling, and create a practical pre-deployment checklist.
1. Environment-based configuration
ASP.NET Core applications commonly run in Development, Staging, and Production environments. The environment can affect error details, configuration files, log levels, and middleware behavior.
In a WebApplication-based project, the current environment can be accessed through builder.Environment or app.Environment:
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsDevelopment())
{
builder.Services.AddOpenApi();
}
var app = builder.Build();
if (app.Environment.IsProduction())
{
app.UseHsts();
}
app.Run();ASP.NET Core loads appsettings.json and then loads the environment-specific file, such as appsettings.Development.json or appsettings.Production.json. Environment-specific values can override general values without requiring code changes.
Example settings files
Non-sensitive and shared settings can be placed in appsettings.json:
{
"Application": {
"Name": "CleanArchitectureApi",
"PublicBaseUrl": "https://api.example.com"
},
"Jwt": {
"Issuer": "CleanArchitectureApi",
"Audience": "CleanArchitectureClient",
"ExpirationMinutes": 30
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}During development, more detailed logging may be useful:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information"
}
}
}In production, framework logs can usually be reduced while application logs remain at a controlled level:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning"
}
}
}2. Reading settings with the Options pattern
Reading IConfiguration directly in every class spreads configuration keys throughout the application. A strongly typed options class makes configuration easier to understand, validate, and test.
For example, we can define a JWT options class:
public sealed class JwtOptions
{
public const string SectionName = "Jwt";
public required string Issuer { get; init; }
public required string Audience { get; init; }
public required string SigningKey { get; init; }
public int ExpirationMinutes { get; init; }
}Register the options in the API project's Program.cs file:
builder.Services
.AddOptions<JwtOptions>()
.Bind(builder.Configuration.GetSection(JwtOptions.SectionName))
.Validate(options => !string.IsNullOrWhiteSpace(options.Issuer),
"JWT issuer is required.")
.Validate(options => options.SigningKey.Length >= 32,
"JWT signing key must contain at least 32 characters.")
.ValidateOnStart();ValidateOnStart ensures that missing or invalid settings are detected when the application starts instead of waiting until the first request. Failing early makes configuration problems more visible in production.
A service can consume the settings through IOptions<JwtOptions>. For settings that may change while the application is running, IOptionsMonitor<JwtOptions> can be considered:
public sealed class TokenService(IOptions<JwtOptions> options)
{
private readonly JwtOptions _options = options.Value;
public string GetIssuer() => _options.Issuer;
}3. Connection strings and secret management
Connection strings, JWT signing keys, SMTP passwords, and third-party API keys must not be stored in source code. Committing these values to a Git repository is dangerous because they may remain available in the repository history even after the file is deleted.
For local development, use User Secrets. Run the following command in the API project directory:
dotnet user-secrets initThen add development-only secrets:
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=localhost;Database=CleanArchitectureDb;Trusted_Connection=True;TrustServerCertificate=True"
dotnet user-secrets set "Jwt:SigningKey" "development-only-key-with-at-least-32-characters"In production, secrets can be supplied through environment variables, container secret mechanisms, or a dedicated secret store such as Azure Key Vault. The application can still read the values using the same configuration keys.
Hierarchical configuration keys are commonly represented with double underscores in environment variables:
ConnectionStrings__DefaultConnection=Server=prod-sql;Database=CleanArchitectureDb;User Id=api_user;Password=secret
Jwt__SigningKey=production-secret-key
Jwt__Issuer=CleanArchitectureApi
Jwt__Audience=CleanArchitectureClientThe important rule is not to place production secrets in appsettings.Production.json. That file may be included in a deployment package and may accidentally be committed, exposed, or printed during troubleshooting.
4. Meaningful structured logging
Logging is more than writing error messages to the console. Production logs should explain when an event occurred, which operation was running, and which identifiers were involved. ASP.NET Core provides structured logging through ILogger<T>.
When logging from an application service, the logger can be injected directly into the implementation. Here is a simple example:
public sealed class OrderService(
IOrderRepository orderRepository,
ILogger<OrderService> logger)
{
public async Task<OrderDto> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
logger.LogDebug("Loading order {OrderId}", id);
var order = await orderRepository.GetByIdAsync(id, cancellationToken);
if (order is null)
{
logger.LogWarning("Order {OrderId} was not found", id);
throw new NotFoundException("Order was not found.");
}
logger.LogInformation(
"Order {OrderId} loaded with status {OrderStatus}",
order.Id,
order.Status);
return OrderDto.FromEntity(order);
}
}Named placeholders such as {OrderId} allow the logging system to preserve searchable fields instead of producing only an unstructured text message. Never log passwords, access tokens, complete connection strings, or unnecessary personal data.
Log levels
| Level | Purpose |
|---|---|
| Trace | Very detailed diagnostic information |
| Debug | Development and troubleshooting information |
| Information | Normal application workflow events |
| Warning | Unexpected conditions that do not stop the application |
| Error | Operations that failed |
| Critical | Conditions threatening application availability |
Using log scopes
A scope can add a common correlation or user identifier to multiple log entries:
public async Task HandleAsync(Guid userId, CancellationToken cancellationToken)
{
using var scope = _logger.BeginScope(new Dictionary<string, object>
{
["UserId"] = userId
});
_logger.LogInformation("Starting user profile operation");
await DoWorkAsync(cancellationToken);
_logger.LogInformation("User profile operation completed");
}In production, the console provider, a centralized logging platform, or a cloud monitoring provider may be used. The provider is important, but consistent, safe, and useful log events should be designed first.
5. Preparing the production pipeline
Detailed exception pages are useful during development, but production users should not receive stack traces or internal implementation details. Combine the centralized exception handler from the previous lesson with production-specific behavior:
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Health checks can be used to monitor whether the application and its critical dependencies are available:
builder.Services.AddHealthChecks()
.AddSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")!);
var app = builder.Build();
app.MapHealthChecks("/health");Whether the health endpoint should be publicly accessible depends on the deployment environment. A load balancer may need a simple readiness endpoint, while an internal operations endpoint may perform a deeper database check.
6. Pre-deployment checklist
- Is the production environment name configured correctly?
- Are production connection strings and JWT keys excluded from source control?
- Does options validation run during application startup?
- Are detailed developer exception pages disabled in production?
- Do logs avoid passwords, tokens, and unnecessary personal data?
- Do important success and failure events contain useful structured fields?
- Are HTTPS and required security headers enabled?
- Is the health check endpoint integrated with the deployment platform?
- Are the release build and database migration strategies defined?
- Are log retention, access control, and monitoring costs planned?
Common mistakes
- Putting secrets in appsettings files: Use User Secrets for local development and a secure secret mechanism for production.
- Logging everything at Information level: Excessive logs create noise and increase storage costs. Configure levels by category.
- Using string interpolation: Prefer named structured placeholders instead of
$"Order {id}". - Returning raw exception messages: Use centralized error handling to avoid leaking internal information.
- Assuming that an open port means the system is ready: The application may still be unable to reach SQL Server or another dependency. Use health checks.
Practice exercise
Task: Create an ApplicationOptions class in your project. It should contain the application name, maximum page size, and external service timeout. Register it with ValidateOnStart.
- Add different values to
appsettings.jsonandappsettings.Development.json. - Override the production values with environment variables.
- Consume the options in an application service.
- Add appropriate log levels for startup, successful operations, and failures.
- Run the
/healthendpoint and verify the application status.
Conclusion
In this lesson, we moved the application beyond a development-only project and prepared it for real operational conditions. Environment-based configuration, strongly typed options, secure secret management, structured logging, and health checks work together to create an API that is observable and maintainable.
At this stage, the application has a stronger foundation for deployment. The next step is to automate packaging and deployment, publish the application, and monitor it in its target runtime environment.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=windows&view=aspnetcore-10.0