This video is available to students only

Creating a Not found Endpoint

In this lesson, we're going to create a not found endpoint

Creating a Not found endpoint#

Right now, if our client hits an endpoint which doesn't exist, they won't see any message, but we want to change that. We want them to get a consistent error message in all possible conditions. The idea is to create a new controller which will work as a redirect controller. Whenever an endpoint is not available, it will be redirected to this controller. Let's create a new controller and call it RedirectController.

This one is going to be a little different. We are going to override the route that we will get from the BaseController; we will write Route here. We can write redirect/code inside curly brackets. The code is our placeholder which will be replaced by the status code. let's import Route from AspnetCore.Mvc to get access to this route.

Now let's add the middleware to redirect an unknown route to the RedirectController, since this is going to be a part of our configure method. Order is really important here, so let's keep it here. Now we will use app.UseStatusCodePagesWithReExecute. Inside, we will pass our route which is redirect, followed by the placeholder, 0.

What will happen is if there's a request for an endpoint that doesn't exist, it will send it our redirect route and 0 will be replaced with the status code which will be 404. Let's go to our redirect controller.

Start a new discussion. All notification go to the author.