Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

ASP.NET Core Exception Handling Middleware

benjamin-abt.com
February 20, 2018 2 min read BEN ABT
ASP.NET Core

This article was written in 2018. Versions, tools and recommendations may have changed since then. Newer posts are collected under ASP.NET Core.

I like my ASP.NET Core controllers and actions very clean and I recommend to not catch all Exceptions inside your Action.

You can have it much easier and simplier - with your custom Exception Middleware.

For exemaple I want to catch all NotImplementedException (I hope you do not have any of them in your final code) and return the HTTP status code 501 (HttpStatusCode.NotImplemented) I can just use this middleware implementation:

C#
 1    public class NotImplementedExceptionMiddleware
 2    {
 3        private readonly RequestDelegate _next;
 4        private readonly ILogger<NotImplementedExceptionMiddleware> _logger;
 5
 6        public NotImplementedExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
 7        {
 8            _next = next ?? throw new ArgumentNullException(nameof(next));
 9            _logger = loggerFactory?.CreateLogger<NotImplementedExceptionMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
10        }
11
12        public async Task Invoke(HttpContext context)
13        {
14            try
15            {
16                await _next(context);
17            }
18            catch (NotImplementedException ex)
19            {
20                if (!context.Response.HasStarted)
21                {
22                    int errorCode = (int)HttpStatusCode.NotImplemented;
23
24                    context.Response.Clear();
25                    context.Response.StatusCode = errorCode;
26                    context.Response.ContentType = "application/json";
27
28                    // this is a sample error result object
29                    ErrorResult error = new ErrorResult("Not implemented", ex.Message);
30                    await context.Response.WriteAsync(error.ToJson());
31                }
32            }
33        }
34    }
C#
1A simple extention to register the middleware cleaner:
2
3    public static class NotImplementedExceptionMiddlewareExtensions
4    {
5        public static IApplicationBuilder UseNotImplementedExceptionMiddleware(this IApplicationBuilder builder)
6        {
7            return builder.UseMiddleware<NotImplementedExceptionMiddleware>();
8        }
9    }

And register this middleware:

C#
 1    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 2    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IPingPongService pingPongService)
 3    {
 4        if (env.IsDevelopment())
 5        {
 6            app.UseDeveloperExceptionPage();
 7        }
 8
 9        // Use Middleware
10        app.UseNotImplementedExceptionMiddleware();
11
12        app.UseMvc(); 
13    }

Done.

Related articles

Production Rate Limiting in ASP.NET Core

Nov 3, 2026 - 16 min read

Production Rate Limiting in ASP.NET Core

Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Production Rate Limiting in ASP.NET Core

Production Rate Limiting in ASP.NET Core

Nov 3, 2026
The Big Decimal Bugfix with .NET 11

The Big Decimal Bugfix with .NET 11

Nov 2, 2026
Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026

Tags

.NET (195) Csharp (99) ASP.NET Core (49) Azure (41) DevOps (17) Docker (15) Microsoft (14) EF Core (11) Microsoft MVP (11) Security (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Synology (9) .NET 11 (8) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact