I have checked that some users experience this error 404 when deploying ASP.NET Core applications and I decide to write this tutorial. I hope it will fix the issue.

Fix 404 Error ASP.NET Core

I found 2 ways to handle 404 error. In fact using these solution you can handle any HTTP status code errors. To handle the error, both the solution are using configure() method of Startup.cs class. For those who are not aware about Startup.cs, it is entry point for application itself.

Solution 1

Now coming back to our solution 1, within configure method define a custom middleware via app.Use which checks for status code value in response object. And if is 404 then it redirects to Home controller. See highlighted code.

Solution 2

The other solution is to use a built-in middlware StatusCodePagesMiddleware. This middleware can be used to handle the response status code is between 400 and 600. This middleware allows to return a generic error response or allows you to also redirect to any controller action or another middleware. See below all different variations of this middleware.

Now to handle the 404 error, we shall use app.UseStatusCodePagesWithReExecute which accepts a path where you wish to redirect.

So we are redirecting here to Home Controller and Errors action method.

The {0} is nothing but the HTTP status error code. Below is the implementation of Errors action method.It adds the status code in ViewData and then returns to Error.cshtml shared view. You can also return to specific error page based on the error code.


So, if the error code is 500 or 404 then return to Home/Error/500.cshtml or 404.cshtml.

You must have seen on many websites, forums about app.UseErrorPage(); to handle the errors. But this is no longer available with RC1 release of ASP.NET Core 1.0. This was available until beta 5 or 6.

Leave a comment

Your email address will not be published.