How do I catch the http status code of server errors into a generic custom error view in ASP.NET MVC

后端 未结 2 1328
面向向阳花
面向向阳花 2020-12-20 01:28

I am trying to implement a general custom error page in ASP.NET MVC 4. I basically set up an Error Layout, which defines a section for outputting the http status code of the

2条回答
  •  既然无缘
    2020-12-20 01:55

    If you're using IIS7+ I'd disable "customerrors" like so:

     
    

    and use httpErrors like so:

    
     
         
         
     
    ....
    

    This allows you to get a non-url changing error page displaying with a 404 status code using the following in your controller:

    public class ErrorController : Controller
    {
    public ActionResult notfound()
        {
            Response.TrySkipIisCustomErrors = true;
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return View("OneErrorViewToRuleThemAll");
        }
    }
    

    ps. "errorMode" needs to change to "Custom" to see it locally....depending on your local setup (i.e. if you're using IISExpress) you might not see the proper error until you upload to a live server.

    pps. you could have the single view "OneErrorViewToRuleThemAll" to handle the on-screen output of whatever status codes you decide to handle this way. Each ErrorController Action would end up on this view.

提交回复
热议问题