ASP.NET MVC ActionFilter

时间:2010-08-25 20:16:38

标签: c# asp.net asp.net-mvc action-filter

是否有人知道ActionFilterAttribute类中的OnResultExecuted方法是否在CATCH块中执行?

即:

        [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?
            }
[...]

2 个答案:

答案 0 :(得分:10)

简而言之:

您可以使用简单的日志记录操作过滤器验证这一点。

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");
    }

}

如果在方法上放置[Log]属性,即使吞下异常,也会看到OnResultExecuted被写入调试。

答案 1 :(得分:2)

我不明白为什么不会。你吞下了这个错误。

退出捕获感觉很脏。你可以在不退出捕获的情况下实现同样的目标:

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

           Usuarios usarios = new Usuarios();

           try
           {
             ...
             usarios = sceUsuarios.Usuario;

            }
            catch  { /*swallow error*/ }

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

           [...]

    }