I have seen a nice example whereby the MVC controller class inherits from another controller class which handles an exception and returns a view with the error inside like so:
public class ApplicationController : Controller
{
public ActionResult NotFound()
{
return View("NotFound");
}
public ActionResult InsufficientPriveleges()
{
return View("InsufficientPriveleges");
}
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is NotFoundException)
{
filterContext.Result = NotFound();
filterContext.ExceptionHandled = true;
return;
}
if (filterContext.Exception is InsufficientPrivelegesException)
{
filterContext.Result = InsufficientPriveleges();
filterContext.ExceptionHandled = true;
return;
}
base.OnException(filterContext);
}
}
However, I’ve noticed that say for example my controller is loading in a partial view for something the user should not have access to, the error will then be shown inside the partial view on the page.
I’d like the whole page to show the error, in effect the exception should redirect to a completely new page. How can I achieve this using the current class shown above?
You can create a mapping from HTTP result codes to specific error handlers in your web.config:
and then create a custom error controller
and then throw an HttpException from your controllers
another alternative is to use a custom FilterAttribute to check permissions which throws a HttpException