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.
Exceptions thrown in the
OnActionExecutingwill be handled by the globalHandleErrorAttribute. You just need to ensure that in your web.config you have enabled it:This being said you talked about an
AuthenticateAttributeand theOnActionExecutingevent. Those two notions are incompatible. If you are writing a custom authorization attribute you should be probably deriving fromAuthorizeAttributeand overriding theAuthorizeCoremethod for the authentication and theHandleUnauthorizedRequestmethod for handling the unauthorized case.You also have the possibility if you don’t want to use the global
HandleErrorAttributeto do the following instead of throwing exceptions:Setting a result inside an action attribute will short-circuit the execution of the controller action and directly render the view.