How do I set ExceptionHandled on an ActionExecutedContext
I'm using an ActionFilter (that I did not write) on an action method. The action method itself calls a SaveOrUpdate() method on a repository. If that SaveOrUpdate() method fails with an exception I would like to set the Exce开发者_如何转开发ptionHandled property of ActionExecutedContext from within the action method so the OnActionExecuted method will not attempt to commit the transaction.
How can I do that? Is this the right way to approach this or should I be doing this differently?
Here's the code in OnActionExecuted of the filter:
public void OnActionExecuted(ActionExecutedContext filterContext)
{
var thereWereNoExceptions = filterContext.Exception == null || filterContext.ExceptionHandled;
if (filterContext.Controller.ViewData.ModelState.IsValid && thereWereNoExceptions)
{
_transaction.Commit();
}
else
{
_transaction.Rollback();
}
}
You don't need to do this. Just throw an exception:
[MyFilter]
public ActionResult Index()
{
throw new Exception("foo");
}
and the else
statement of your OnActionExecuted
filter will be hit and rollback the transaction.
Here is the code I use to handle custom errors.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
精彩评论