1

I catch and redirect 404 errors to an Error controller \ views with the following code.

Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "HttpError";
routeData.Values["exception"] = exception;          

Response.StatusCode = 500;
//if http 404 redirect to http404 action
if (httpException != null)
{
    Response.StatusCode = httpException.GetHttpCode();
    switch (Response.StatusCode)
    {
        case 404:
            routeData.Values["action"] = "Http404";
            break;
    }
}

In the error controller if I set Response.StatusCode = (int)HttpStatusCode.NotFound I get the generic error handler, not the view I returned. This only seems to happen in production. Any ideas why?

[AllowAnonymous]
public ActionResult Http404()
{
    //this line causes generic error handler
    Response.StatusCode = (int)HttpStatusCode.NotFound;

    var viewModel = new ErrorViewModel
    {
        Description = "Hmm, the page you're looking for can't be found"
    };

    return View("Error", viewModel);
}
Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60
NullReference
  • 4,404
  • 12
  • 53
  • 90

1 Answers1

0

If you are setting a custom StatusCode in your controller's action method, and want to override default error handling, you need to do one of the following:

  • Set Response.TrySkipIisCustomErrors = true in the controller method
  • Define the following in your Web.config:

    <system.webServer> <httpErrors existingResponse="PassThrough"></httpErrors> </system.webServer>

More detail here: https://stackoverflow.com/a/22477783/459102

Community
  • 1
  • 1
Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60