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.”); } }
Verify your domain for Improper Error Handling in 3 seconds
Run 20+ passive checks (TLS/RDAP expiry, CSP, DMARC, source maps, CT subdomains) and get stack-exact copy-paste fixes for ASP.NET Core.
Verified by GuardAPI Deterministic Engine
Remediation snippets and external posture guides maintained for modern cloud stacks (Next.js, Cloudflare, Nginx, Vercel, OVH).