I’m working on a new .Net Core MVC project where I have a front facing site and an area called “App” where signed up users will spend their time.

The default OTB .net core project has the following in Startup.cs


if (env.IsDevelopment())

The problem with this approach is that first there’s no 404 catching as that’s not technically an exception and secondly, my front facing site and App area have two very different layouts. What happens then, is that if an exception occurs under App the user will get redirect to the supplied path making it difficult to get back to the App section.

Enter Middleware. You can see the complete code on GitHub.

I’m not entirely happy with this method as I couldn’t find a nice way to get the route data as it’s too early in the pipeline in .net core. Unfortunately, this leads to magic strings which I despise. It also means that each area will have to be consider. If you add a new area and need error handling for that area separately from the root, you will have to modify the middleware.

I borrowed the code from Microsoft.AspNetCore.Diagnostics/Internal/DiagnosticsLoggerExtensions.cs on github (the source code behind UseExceptionHandler) and enhanced it in two ways to cover my issues mentioned above.

First, I get the area from the request path by using StartsWith. For this project I have three filters, one for App, one for api and one for signin.

After I have the area I try to call the next delegate and wait for the success or failure. If there’s no exception I want to check if our call is to an api or not. If it is, I don’t want the middleware to do anything less as I’m likely returning a 404 error from the api on purpose. Since I am using external login service I also want to skip if the path starts with /signin (e.g. /signin-Google) as this is handled by Identity.

If there’s a 404 then redirect to the error controller and the NotFound action.

The rest of the code is basically the copy from the OTB UseExceptionHandler except I’m rebuilding the redirect path based on the area and the options provided.