Search code examples
asp.netasp.net-mvchttp-status-code-404application-error

Server.Transfer cannot render an MVC-View


In my Application_Error event handler i want to render an MVC-View for 404. I do not want to redirect because of SEO.

void Application_Error(...)
{
 if (serverException is HttpException && ((HttpException)serverException).GetHttpCode() == 404)
 {
  Server.Transfer("/error/404"); //*
 }
}

//* Fails, because it cannot find the path on disk. Of course not because it should be handled by MVC.

How to render an MVC-View from Application_Error?

I do not want to redirect.


Solution

  • Just don't use Application_Error to handle 404 errors. Define a catch all route:

    routes.MapRoute(
        "Error", 
        "{*url}", 
        new { controller = "Error", action = "Http404" });
    

    A request that doesn't match another route will be handled by the Http404 action of the Error controller.