I understand how to set up my own routes, but how does one handle routes that fall through the cracks of the routing table? I mean, I guess the default {controller}/{action}/{id}
route could be a generic catchall, but I'm not sure if that's the way to go. I like letting my users know they've requested data/a 'page' that doesn't exist.
Is this where the [HandleError]
filter comes in? How does that work, exactly?
To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.
If your route is not found, you want to handle it as a normal HTTP 404 error.
If you only add the [HandleError]
attribute to your class or action, MVC will look for an Error
view in your views folder.
You could also add an ErrorController
or even a static page and add this to your Web.config
:
<customErrors mode="On" >
<error statusCode="404" redirect="/Error/PageNotFound/" />
</customErrors>
Or you could handle the HTTP 404 in your Global.asax.cs
and route to an ErrorController
programmatically. That's how I generally do it:
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError().GetBaseException();
var routeData = new RouteData();
if (ex.GetType() == typeof(HttpException))
{
var httpException = (HttpException)ex;
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values.Add("action", "PageNotFound");
break;
default:
routeData.Values.Add("action", "GeneralError");
break;
}
}
else
{
routeData.Values.Add("action", "GeneralError");
}
routeData.Values.Add("controller", "Error");
routeData.Values.Add("error", ex);
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
You can define a route like this:
routes.MapRoute(
"PageNotFound",
"{*catchall}",
new { controller = "Home", action = "PageNotFound" }
);
Than make an action in a controller like this:
public ActionResult PageNotFound()
{
ViewBag.Message = "Sorry, the page you requested does not exist.";
return View();
}
This route sould be added last, that way it will catch any request that can't be mapped.
HandleError
attribute is used to catch exceptions that may occure within controller actions.
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