ASP.NET Core middleware
Context: In ASP.NET Core, global exception handling is typically implemented as custom middleware. The middleware catches exceptions thrown by subsequent middleware and pipeline components, logs them, and returns a consistent error response (e.g., a JSON error object or a custom error page). This keeps API responses uniform and avoids exposing internal details.
Usage Example
Section titled “Usage Example”using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Logging;using System;using System.Threading.Tasks;
public class ExceptionHandlingMiddleware{ private readonly RequestDelegate _next; private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger) { _next = next; _logger = logger; }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, "An unhandled exception occurred."); context.Response.StatusCode = 500; await context.Response.WriteAsJsonAsync(new { error = "Internal server error." }); } }}
// Extension method to register the middlewarepublic static class ExceptionHandlingExtensions{ public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder builder) { return builder.UseMiddleware<ExceptionHandlingMiddleware>(); }}
// In Program.cs: app.UseGlobalExceptionHandler();Output console (when an exception occurs)
Section titled “Output console (when an exception occurs)”HTTP/1.1 500 Internal Server Error{"error":"Internal server error."}Important notes
Section titled “Important notes”- Middleware order matters; place exception middleware early.
- For development, use
UseDeveloperExceptionPagefor detailed errors. - Can differentiate between API and UI responses.
Real-world usage example
Section titled “Real-world usage example”Production APIs – Return RFC 7807 Problem Details for errors.
See .NET docs on exception middleware.