views:

66

answers:

2

Does anybody knows if the OnResultExecuted method from ActionFilterAttribute class is executed even in CATCH block?

ie:

        [CookiesActions]
        public ActionResult Login(Usuarios usuario)
[...]
            return View(new UsersViewModel(sceUsuarios.Usuario,true));
            }
            catch
            {
                return View(new UsersViewModel(new Usuarios(),true));//is OnResultExecuted fired here?
            }
[...]
A: 

I don't see why it wouldn't. You are swallowing the error.

Returning out of a catch feels dirty. You could achieve the same thing without returning out of a catch:

   [CookiesActions]
    public ActionResult Login(Usuarios usuario)
    {
     [...]

           Usuarios usarios = new Usuarios();

           try
           {
             ...
             usarios = sceUsuarios.Usuario;

            }
            catch  { //swallow error }

            return View(new UsersViewModel(usarios ,true));

           [...]

    }
Chuck Conway
I cannot do that,cause i want to execute OnResultExecuted logic only if no exceptions occurs
You could store a flag in the HttpContext.Items collection. In the catch you could set the flag. In the OnResultExecuted check for the flag... It's a bit kludgy... but it would work.
Chuck Conway
+1  A: 

In short: YES.

You can verify this with a a simple logging action filter.

public class LogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Log("OnActionExecuting", filterContext.RouteData);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Log("OnActionExecuted", filterContext.RouteData);
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Log("OnResultExecuting", filterContext.RouteData);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Log("OnResultExecuted", filterContext.RouteData);
    }


    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }

}

If you put the [Log] attribute on your method, you'll see that OnResultExecuted is written to debug even when you swallow the exception.

Peter