How can I properly handle 404 in ASP.NET MVC?-Collection of common programming errors

For the lazy guys out there:

Install-Package MagicalUnicornMvcErrorToolkit -Version 1.0

Then remove this line from global.asax

GlobalFilters.Filters.Add(new HandleErrorAttribute());

And this is only for IIS7+ and IIS Express.

If you’re using Cassini .. well .. um .. er.. awkward …

Long, explained answer

I know this has been answered. But the answer is REALLY SIMPLE (cheers to David Fowler and Damian Edwards for really answering this).

There is no need to do anything custom.

For ASP.NET MVC3, all the bits and pieces are there.

Step 1 -> Update your web.config in TWO spots.


    
      
    

and


    
      
      
      
      
        

...

...

Now take careful note of the ROUTES I’ve decided to use. You can use anything, but my routes are

  • /NotFound axd's and favicons (ooo! bonus ignore route, for you!) Then (and the order is IMPERATIVE HERE), I have my two explicit error handling routes .. followed by any other routes. In this case, the default one. Of course, I have more, but that’s special to my web site. Just make sure the error routes are at the top of the list. Order is imperative.

    Finally, while we are inside our global.asax file, we do NOT globally register the HandleError attribute. No, no, no sir. Nadda. Nope. Nien. Negative. Noooooooooo…

    Remove this line from global.asax

    GlobalFilters.Filters.Add(new HandleErrorAttribute());
    

    Step 3 – Create the controller with the action methods

    Now .. we add a controller with two action methods …

    public class ErrorController : Controller
    {
        public ActionResult NotFound()
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return View();
        }
    
        public ActionResult ServerError()
        {
            Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    
            // Todo: Pass the exception into the view model, which you can make.
            //       That's an exercise, dear reader, for -you-.
            //       In case u want to pass it to the view, if you're admin, etc.
            // if (User.IsAdmin) //

Originally posted 2013-08-11 02:47:20.