Home > DeveloperSection > Forums > 404 page not found error for an ASP.NET MVC application
Monaj Singh
Monaj Singh

Total Post:41

Points:287
Posted on    November-09-2014 10:40 PM

 ASP.NET MVC Mvc4  Error 
Ratings:


 1 Reply(s)
 701  View(s)
Rate this:
Hi Guys

This must be simple and already answered, but I've wasted many hours on it. I can't figure how to get an error page on mistyped address. Also I'd prefer not to redirect, but to keep the URL. I've tried many combinations of CustomErrors, HttpErrors and Application_Error, but nothing works for non-existent controller - depending on HttpErrors I always get IIS 404.0 page or just an empty 404 response. Running on IIS 7.5, MVC 3.


David Miller

Total Post:30

Points:210
Posted on    November-10-2014 12:51 AM

I don't remember where I got the solution. But here is the code to handle the error: First, you create a ErrorController:

public class ErrorController : Controller

{

    //

    // GET: /Error/

    public ActionResult Index()

    {

        return RedirectToAction("Index", "Home");

    }

 

    public ActionResult Generic()

    {

        Exception ex = null;

        try

        {

            ex = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];

        }

        catch { }

 

        return View();

    }

 

    public ActionResult Error404()

    {           

        return View();

    }

}

Second, open Global file and add the following code:

protected void Application_Error(object sender, EventArgs e)

{

     Exception ex = Server.GetLastError();

     Application[HttpContext.Current.Request.UserHostAddress.ToString()] = ex;

}

Third, change customerror in your webconfig:

<customErrors mode="Off" defaultRedirect="/Error/Generic">

  <error statusCode="404" redirect="/Error/Error404"/>

</customErrors>

More: I created one more error layout. It makes things even more clear. :) 


Don't want to miss updates? Please click the below button!

Follow MindStick