Introduction
Unexpected failures are unavoidable in a real content management application. A database connection can become temporarily unavailable, an external service can fail, or an unexpected input can expose a condition that was not considered during development. The goal is not merely to catch every exception. The goal is to handle failures safely, provide useful diagnostic information to developers, and keep sensitive details away from visitors.
In this lesson, we will use ASP.NET Core MVC and .NET 8 to implement three related capabilities: different error behavior for development and production, structured logging with ILogger, and health checks that report whether the application is operational. By the end, the application will show a safe public error page while still giving developers and administrators enough information to investigate a problem.
Core principle: users should receive a clear and safe message, while developers should receive controlled and actionable diagnostic data.
1. Understanding the error-handling strategy
ASP.NET Core can display detailed exception information in the Development environment. This page may include a stack trace, request headers, cookies, query-string values, and other information that should not be exposed publicly. For this reason, the developer exception page must be limited to development. In production, use UseExceptionHandler to redirect failures to a custom error endpoint.
The exception-handling middleware should be registered early in the pipeline. This allows it to handle unhandled exceptions thrown by later middleware, controllers, and application services.
Configuring Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddProblemDetails();
builder.Services.AddHealthChecks();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapHealthChecks("/health");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();AddProblemDetails helps create standardized error responses. In the MVC user interface, we will display an HTML error view through /Home/Error. If the same application also contains API controllers, the same service can help APIs return Problem Details responses instead of exposing exception data.
2. Creating a production error page
The error page should normally be accessible to anonymous users. An error may occur while an unauthenticated visitor is opening the home page. Requiring authorization for the error action could create a second authorization failure while the application is already trying to report the first failure.
First, create a small view model for the error page:
namespace CmsApp.Models;
public sealed class ErrorViewModel
{
public string? RequestId { get; init; }
public bool ShowRequestId =>
!string.IsNullOrWhiteSpace(RequestId);
}Next, add an error action to HomeController:
using System.Diagnostics;
using CmsApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
return View(new ErrorViewModel
{
RequestId = requestId
});
}
public IActionResult Index()
{
return View();
}
}IExceptionHandlerPathFeature can provide access to the original exception and request path. However, the exception should not be passed to the view for display. Showing only a request ID gives support staff a safe value that can be matched with server logs.
The Views/Home/Error.cshtml view can contain the following markup:
@model CmsApp.Models.ErrorViewModel
@{
ViewData["Title"] = "An error occurred";
}
<h2>We could not process your request</h2>
<p>An unexpected problem occurred. Please try again later.</p>
@if (Model.ShowRequestId)
{
<p>When contacting support, provide this code: <code>@Model.RequestId</code></p>
}
<p><a asp-controller="Home" asp-action="Index">Return to the home page</a></p>The error view should not show an exception message, physical file path, SQL connection string, stack trace, or sensitive form values.
3. Structured logging with ILogger
ASP.NET Core applications create logs through ILogger<T>, which is normally supplied by dependency injection. Log levels describe the importance of an event: Trace, Debug, Information, Warning, Error, and Critical. In production, levels should be controlled through configuration so that unnecessary diagnostic noise can be reduced without recompiling the application.
For example, a content service can log important publishing operations:
using Microsoft.Extensions.Logging;
public sealed class ContentService
{
private readonly ILogger<ContentService> _logger;
private readonly ApplicationDbContext _db;
public ContentService(
ILogger<ContentService> logger,
ApplicationDbContext db)
{
_logger = logger;
_db = db;
}
public async Task PublishAsync(int contentId, CancellationToken cancellationToken)
{
_logger.LogInformation(
"Content publishing started. ContentId: {ContentId}",
contentId);
var content = await _db.Contents
.FindAsync(new object[] { contentId }, cancellationToken);
if (content is null)
{
_logger.LogWarning(
"The content to publish was not found. ContentId: {ContentId}",
contentId);
throw new InvalidOperationException("Content was not found.");
}
content.IsPublished = true;
content.PublishedAtUtc = DateTime.UtcNow;
await _db.SaveChangesAsync(cancellationToken);
_logger.LogInformation(
"Content was published successfully. ContentId: {ContentId}",
contentId);
}
}{ContentId} is a structured message-template property. Passing the value separately instead of concatenating it into a string makes logs easier to search, filter, and analyze in a centralized logging system.
Logging exceptions
When logging an exception, pass the exception object as the first argument. This preserves the stack trace:
try
{
await _contentService.PublishAsync(contentId, cancellationToken);
}
catch (Exception exception)
{
_logger.LogError(
exception,
"An unexpected error occurred while publishing content. ContentId: {ContentId}",
contentId);
return RedirectToAction(nameof(Error));
}The centralized exception middleware may already log unhandled exceptions. Logging the same exception in the controller, service, and middleware can create duplicate and noisy entries. Use Warning for expected business conditions and Error or Critical for unexpected failures that prevent an operation from completing.
Configuring log levels
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"CmsApp": "Debug"
}
}
}Never write passwords, access tokens, credit-card numbers, connection strings, personal data, or sensitive user-submitted content to logs. Logs must be protected like other production data, and their retention period should be defined.
4. Adding health checks
An application process can be running while the application is unable to connect to its database or another required dependency. A health-check endpoint can be called by a load balancer, container platform, or monitoring system to verify basic availability.
For a simple application, AddHealthChecks and MapHealthChecks are sufficient:
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");The endpoint returns HTTP 200 when the registered checks are healthy. In a more realistic application, the database can also be checked. After adding the appropriate EF Core health-check package, the registration can look like this:
builder.Services
.AddHealthChecks()
.AddDbContextCheck<ApplicationDbContext>(
name: "database",
tags: new[] { "ready" });It is useful to distinguish liveness from readiness. The process may still be alive even when the database is unavailable. In that case, the application should not receive normal traffic until its required dependencies are ready. The exact implementation depends on the hosting or orchestration platform.
Creating a custom health check
Application-specific dependencies can be checked by implementing IHealthCheck:
using Microsoft.Extensions.Diagnostics.HealthChecks;
public sealed class ContentHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
var result = HealthCheckResult.Healthy(
"The content service is running.");
return Task.FromResult(result);
}
}Register the custom check with dependency injection and the health-check system:
builder.Services.AddHealthChecks()
.AddCheck<ContentHealthCheck>(
"content-service",
tags: new[] { "ready" });Whether the health endpoint is public or restricted to an internal network is a deployment decision. If it is publicly reachable, avoid returning detailed dependency messages that reveal internal service names or connection failures.
5. Common mistakes
- Enabling the developer exception page in production: Stack traces and request details may reveal sensitive information.
- Displaying Exception.Message directly: Database, filesystem, or service details may leak to users.
- Writing secrets to logs: Logging systems can also become targets for attackers.
- Using try-catch everywhere: Re-handling errors that can be managed centrally makes the code harder to maintain.
- Protecting the error action with authorization: Anonymous visitors may be unable to see the error page.
- Treating a health check as only a process check: Critical databases and services should be checked separately.
- Returning detailed health information publicly: Internal architecture and connection errors should not be disclosed.
6. Practice exercise
- In an MVC project, add
AddProblemDetails,UseExceptionHandler, andMapHealthChecks("/health"). - Create an anonymously accessible
Erroraction and view in the Home controller. - Throw a controlled
InvalidOperationExceptionfrom an action and compare Development and Production behavior. - Inject
ILogger<T>into a service and write one Information, one Warning, and one Error log. - Test a successful health-check response and observe the result when a database check fails.
Conclusion
In this lesson, we made the ASP.NET Core MVC application safer and easier to observe. We used detailed diagnostics only during development, switched to a safe error page in production, recorded important operations with structured ILogger properties, and exposed a health-check endpoint for external monitoring.
As the course moves toward performance and deployment topics, these logs and health checks will become essential tools for understanding application behavior, detecting failures early, and operating the CMS reliably in production.