How to fix Improper Error Handling
in ASP.NET Core
Executive Summary
Leaking stack traces is a gift to the adversary. Improper error handling in ASP.NET Core exposes your tech stack, database schema, and internal logic through verbose exception messages. To harden the app, you must decouple technical failure details from the HTTP response, ensuring only sanitized, generic information reaches the client while preserving full context in secure server-side logs.
The Vulnerable Pattern
public void Configure(IApplicationBuilder app) { // DANGEROUS: Enabling developer page in all environments app.UseDeveloperExceptionPage();app.Run(async context => { try { // Business logic that might fail throw new Exception("Database connection failed for user: admin_db"); } catch (Exception ex) { // LEAK: Sending raw exception details directly to the HTTP response await context.Response.WriteAsync(ex.ToString()); } });
}
The Secure Implementation
The fix involves three pillars: 1. Environment-specific configuration—never invoke UseDeveloperExceptionPage() in production. 2. Centralized Middleware—use UseExceptionHandler to intercept unhandled exceptions globally, preventing the default 'white label' error pages or raw dumps. 3. Standardized responses—implement RFC 7807 (Problem Details) to return consistent, opaque error messages. This mitigates CWE-209 (Information Exposure Through an Error Message) and prevents attackers from fingerprinting your infrastructure and internal code paths.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // Secure: Use a centralized exception handler for production app.UseExceptionHandler("/error"); } }
[Route(“/error”)] [ApiController] [ApiExplorerSettings(IgnoreApi = true)] public class ErrorController : ControllerBase { public IActionResult HandleError() { // RFC 7807 Problem Details - Opaque error for the client return Problem( detail: “A system error occurred. Please contact support with the correlation ID.”, title: “An unexpected error occurred.”); } }
Protect your ASP.NET Core API
Don't rely on manual checks. GuardLabs detects Improper Error Handling and logic flaws in seconds.
Run Free AuditVerified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.