Simple way to handle HTTP status error in ASP.NET core
You can simply handle http status error like HTTP 404 error and any other http status error in ASP .NET by using this simple solution. HTTP 404 is one of the must common error in ASP .NET when the requested error is not found . We can solve the problem by adding some code in the configure() method in Startup.cs class which is also the entry point for the application itself.
In the configure function we define and add a custom middleware with ‘app.Use’ which will check for status code value in response object. In our case we will be taking a solution for the HTTP 404 error and let us redirect the controller to Home Controller when the error is met.
Add the following code inside the Configure() function in Startup.cs file:
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Request.Path = "/Home";
await next();
}
});
After adding the code whenever the status 404 error is met in our program the request is redirected to Home Controller. The same solution can be implemented to other types of HTTP status error by changing the status error value in the code. And by changing the Request path you can redirect the program to any controller.
Also read: Difference between ASPX and Razor View Engine in .Net