How to have a custom 404 and 500 error pages with a stock standard ASP.NET MVC3 website?

后端 未结 3 1261
花落未央
花落未央 2021-02-04 14:05

I\'m trying to have 2 custom error pages in a stock sample ASP.NET MVC3 website.

Darin Dimitrov has a good SO answer here but it\'s not working for all my test condition

3条回答
  •  故里飘歌
    2021-02-04 14:49

    I specify customErrors in my web.config file as below;

        
          
          
          
        

    I have a route in the Global.asax as below;

                /// Error Pages
                /// 
                routes.MapRoute(
                    "Error", // Route name
                    "Error/{errorCode}", // URL with parameters
                    new { controller = "Page", action = "Error", errorCode= UrlParameter.Optional }
                );
    

    The corresponding ActionResult does the following, which returns the relevant custom error page.

    //
            public ActionResult Error(string errorCode)
            {
                var viewModel = new PageViewModel();
    
                int code = 0;
                int.TryParse(errorCode, out code);
    
                switch (code)
                {
                    case 403:
                        viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("403 Forbidden");
                        return View("403", viewModel);
                    case 404:
                        viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("404 Page Not Found");
                        return View("404", viewModel);
                    case 500:
                         viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("500 Internal Server Error");
                        return View("500", viewModel);
                    default:
                        viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("Embarrassing Error");
                        return View("GeneralError", viewModel);
                }
            }
    

    This allows me to have many different custom error pages. It's maybe not the best or most elegant solution, but it certainly works for me.

提交回复
热议问题