News Post

  • How to handle 404 error in ASP.NET Core 1.0

  • Prior versions of ASP.NET Core 1.0, have custom errors for error handling. With ASP.NET Core 1.0 and MVC, you can do the error handling via Middlwares. HTTP 404 is a very common error which comes when server can’t find the requested resource. In this post, we will see different ways to handle HTTP 404 error in ASP.NET Core 1.0 and MVC.          
  • How to handle 404 error in ASP.NET Core 1.0
  • 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. You can read this excellent post The Startup.cs File in ASP.NET Core 1.0. to know more about startup.cs. And within the startup.cs file, you will also find static void main() which generally you use with windows/console applications. Read my post Why static void main in ASP.NET 5 startup.cs 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.




  • 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.

    o, 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. If you come across any other solution, please mention in comments section or send it on twitter/facebook. All these solutions are based on RC1 release of ASP.NET Core. So if anything changes or broken please let us know. Keep visiting for updates and share this in your network. PS: If you found this content valuable and want to return the favour, then