- Lab
- Security

Secure Error Handling for C# Applications
In this lab, you’ll implement secure error handling and structured logging in a .NET 8 Web API. When you’re finished, you’ll have a hardened API that returns safe, user-friendly error messages, captures rich diagnostic logs for developers, and filters sensitive data from all log outputs.

Path Info
Table of Contents
-
Challenge
Getting Started in the Lab Environment
Here are the initial instructions and explanation of the lab environment. Read this while your environment is busy creating itself from nothing. Yes, this violates physics; we know. How fun!
-
Challenge
Why Secure Error Handling Matters
Before you write any code, it's important to understand why secure error handling matters in production APIs. In this challenge, you'll explore key risks: unhandled exceptions that expose stack traces, verbose logs that may leak sensitive information, and differences between Development and Production environments.
-
Challenge
Insecure Error Handling & Noisy Logs
You'll create a basic ASP.NET Core Web API with a /login endpoint that intentionally throws an exception when a password check fails. You'll observe how the framework exposes stack traces and input by default in both Development and Production modes—and why that's insecure without added protections.
-
Challenge
Secure Error Handling & Manual Redaction
You'll create global exception-handling middleware to catch unhandled exceptions and return a safe JSON error response. You'll then ensure full exception details are logged internally and that behavior remains consistent across Development and Production environments.
-
Challenge
Structured Logging with Serilog
You’ll integrate Serilog to produce structured, queryable logs. You’ll configure a JSON file sink, replace Console.WriteLine with Serilog calls, and add masking logic to prevent sensitive data like passwords and tokens from being stored.
-
Challenge
Knowledge Check for Secure Error Handling for C#
To finish the lab, you will answer some assessment questions that will test your understanding of the concepts you learned throughout this lab.
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the author’s guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.