Error Handling Content vs API Routes in ASP.Net Core 2.1


When working with ASP.Net Core web projects, I’ve often run into the situation where a site has both content pages and more interactive front end components that work with back-end API routes. In situations like this, it’s most appropriate for the content routes to forward to some kind of friendly error page if an error code like 500 or 404 is encountered. You know – the typical “Oops… something went wrong!” or “Sorry! We couldn’t find that page”, and so on. Whatever fits your brand.

However, when we’re hitting a route from an ajax method or front-end component to add or retrieve some data (for example), it’s more appropriate to just send the raw error code back and some type of error message back, rather than a redirect/page (could come back as a 200 or 302 http status code), e.g.

400: Bad Request
      The “First Name” field is required



That way, our front end can gracefully handle the issue and display a message to the user however it makes sense.

So how do we support both scenarios? Thankfully, ASP.Net Core 2.1 makes this easy. There are two tools we use together – content page redirection middleware for error codes, and conditional middleware to ensure we don’t redirect in the situations we don’t want to. I usually stipulate that routes that contain /api in their path are to just respond with raw http status codes/messages, rather than redirection. We can add the following code to our project’s Startup.cs Configure method to facilitate this:

The “app.UseWhen” method specifies that we want to only invoke a piece of middleware in a certain scenario. In this case, I’ve stipulated whenever the request path value doesn’t contain /api. In that situation, the middleware “UseStatusCodePagesWithRedirects” is injected. This middleware will redirect our app to a specified error handling route whenever an http status code error of some kind hits. In this situation, /error/{0} will capture whatever error code comes back, so /error/500 or /error/400. This is great for the situations where we want to have a specific page for each type of error code. If this isn’t a requirement, we can just redirect to a friendly generic error page.

That’s it! There are lots of other applications of conditional ASP.Net Core middleware, but I’ve found this one to be very useful for situations where you need to have both API and content routes in an app, but don’t want to split them up into multiple projects.