2

I've tried to fix my error handling for MVC a bit and implemented Marco's solution from here:
ASP.NET MVC 404 Error Handling

This works perfectly on my Win7 workstation. But for some reason it does not work on the server. Certain errors work fine, but for example if I call a controller and route that does not exist I get the standard IIS 404 page.

I've put in some logs and the Error404Controller is called and executed, but for some reason the processing does not stop and it loads the IIS 404 error page afterwards.

This is the code in my global.asax

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 404)
    {
        Response.Clear();

        var rd = new RouteData();
        rd.Values["controller"] = "Error404";
        rd.Values["action"] = "Index";

        IController c = new SuperMvc.Controllers.Error404Controller();
        c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
    }
}

And this the controller:

[AcceptVerbs(HttpVerbs.Get)]
public virtual ActionResult Index()
{
    log.Error("Error404Controller.Index");

    PageError error = new PageError();

    error.Url = Request.Url.AbsoluteUri;
    log.Error("Request.Url=" + error.Url);

    error.UrlReferrer = Request.UrlReferrer.AbsoluteUri;
    log.Error("Request.UrlReferrer=" + error.Url);

    return View(error);
}

Any ideas? I checked the web.config files and can't find a difference.

Community
  • 1
  • 1
Remy
  • 12,555
  • 14
  • 64
  • 104
  • When you try a controller/action that doesn't exist, have you logged the status code? Is it definitely a 404 by the time it gets to this point? (I'm thinking sometimes I used to get blah doesn't implement IController - which would be a code 500) – Carl Oct 03 '14 at 11:14
  • No, I do get a 404 response code in Application_EndRequest and the Error404Controller gets called, but I still get the the IIS 404 error page instead of mine. – Remy Oct 16 '14 at 12:42

1 Answers1

2

If in IIS7, you will need to tell IIS7 to ignore the custom error pages, using Response.TrySkipIisCustomErrors = true;. This will disable the IIS custom error pages for that response, as per the msdn.

So your Application_EndRequest may look like this:

protected void Application_EndRequest()
{
    if (Context.Response.StatusCode == 404)
    {
        Response.Clear();

        var rd = new RouteData();
        rd.Values["controller"] = "Error404";
        rd.Values["action"] = "Index";

        Response.TrySkipIisCustomErrors = true;
        IController c = new SuperMvc.Controllers.Error404Controller();
        c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
    }
}
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112