How to make custom error pages work in ASP.NET MVC 4

前端 未结 11 2114
陌清茗
陌清茗 2020-11-22 12:25

I want a custom error page shown for 500, 404 and 403. Here\'s what I have done:

  1. Enabled custom errors in the web.config as follows:

    
    
            
11条回答
  •  死守一世寂寞
    2020-11-22 13:09

    There seem to be a number of steps here jumbled together. I'll put forward what I did from scratch.

    1. Create the ErrorPage controller

      public class ErrorPageController : Controller
      {
          public ActionResult Index()
          {
              return View();
          }
      
          public ActionResult Oops(int id)
          {
              Response.StatusCode = id;
              return View();
          }
      }
      
    2. Add views for these two actions (right click -> Add View). These should appear in a folder called ErrorPage.

    3. Inside App_Start open up FilterConfig.cs and comment out the error handling filter.

      public static void RegisterGlobalFilters(GlobalFilterCollection filters)
      {
          // Remove this filter because we want to handle errors ourselves via the ErrorPage controller
          //filters.Add(new HandleErrorAttribute());
      }
      
    4. Inside web.config add the following entries, under System.Web

      
          
          
      
      
    5. Test (of course). Throw an unhandled exception in your code and see it go to the page with id 500, and then use a URL to a page that does not exist to see 404.

提交回复
热议问题