asp.net-mvc-3exceptionaction-filterhandleerror

Is it possible to have ActionFilter exceptions handled via the [HandleError] mechanism?


I have a custom action filter (AuthenticateAttribute) in my ASP.NET MVC 3 application that ensures that users are logged in.

I want to raise exceptions in the OnActionExecuting method and would like those to be handled by the HandleError global filter. Is that possible and, if so, how do I do it?

Currently, raising an exception in OnActionExecuting bypasses the HandleError global filter - presumably because that only traps exceptions that occur within the action iself.


Solution

  • Exceptions thrown in the OnActionExecuting will be handled by the global HandleErrorAttribute. You just need to ensure that in your web.config you have enabled it:

    <customErrors mode="On" />
    

    This being said you talked about an AuthenticateAttribute and the OnActionExecuting event. Those two notions are incompatible. If you are writing a custom authorization attribute you should be probably deriving from AuthorizeAttribute and overriding the AuthorizeCore method for the authentication and the HandleUnauthorizedRequest method for handling the unauthorized case.

    You also have the possibility if you don't want to use the global HandleErrorAttribute to do the following instead of throwing exceptions:

    filterContext.Result = new ViewResult
    {
        ViewName = "~/Views/Shared/401.cshtml"
    };
    

    Setting a result inside an action attribute will short-circuit the execution of the controller action and directly render the view.