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 conditions.
Then there is the widely popular How can I properly handle 404s in ASP.NET MVC? post .. but this just touches on a 404 error.
Can someone please explain what
web.config
settingsare required to do this very simple thing :(
Scenarios to accept this answer:
ErrorController
)...and for the test routes...
/Home/Index
-> shows index page/Home
-> shows index page/
-> shows index page/Home/About
-> shows about page/asdasd/asdsad/asdas/asddasd/adsad
-> 404/adsa/asda/asd/asd/asd/asd
-> 404/asdsadasda
-> 404then add this to the HomeController.cs
class..
public ActionResult ThrowException()
{
throw new NotImplementedException();
}
and now ..
/home/throwexception
-> 500 errorCheers :)
BTW, some of those realy long routes (above) give really weird error pages right now, when using the stock standard new ASP.NET MVC3
template
aspx. Add the Application_Error event to the Global. asax file to trap the error that you throw in the Page_Load event of the AppEvent. aspx page.
Custom error pages enable you to customize the pages that display when an error occurs. This makes your website appear more professional and also prevents visitors from leaving your site. If a visitor sees a generic error page, they are likely to leave your site.
I specify customErrors in my web.config file as below;
<customErrors defaultRedirect="/Error/GeneralError" mode="On">
<error statusCode="403" redirect="/Error/403" />
<error statusCode="404" redirect="/Error/404" />
<error statusCode="500" redirect="/Error/500" />
</customErrors
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With