MVC ActionExecutedContext类的ExceptionHandled属性返回false

时间:2017-12-06 18:51:16

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

我的行动如下

[Audit()]
public ActionResult Submit(Employee employee)
{
     try
     {
          throw new Exception(); 
     }
     catch(Exception ex)
     {
          return new EmptyResult();
     }
}

动作过滤器类如下

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else
    }
}

但是,ExceptionHandled属性总是返回false,即使处理异常,因为它在代码中很清楚,任何想法可能是什么问题?

1 个答案:

答案 0 :(得分:0)

如果您在基类中覆盖OnActionExecuted,则应检查此实现是否不会更改filterContext.ExceptionHandled的状态。如果是这种情况,那么您应该在方法结束时调用base.OnActionExecuted(filterContext);

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}

否则,我建议您检查ActionExecutedContext背景中是否有exceptions

public class AuditAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //base.OnActionExecuted(filterContext);

        if (filterContext.Exception == null) //Do something

        if(filterContext.ExceptionHandled == true) // Do something
        else // Do something else

        base.OnActionExecuted(filterContext);
    }
}