如何允许自定义异常筛选器在异常期间继续调用指定的操作方法

本文关键字:调用 继续 操作方法 自定义异常 何允许 筛选 异常 | 更新日期: 2023-09-27 18:32:05

当我的异常过滤器被调用时,我希望仍然调用控制器中的预期操作。我创建了以下IExceptionFilter:

    public class ArgumentExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception.GetType() == typeof(System.ArgumentException))
            {
                //Some logic to create a default "SettingsRoot" parameter
                //This simply surpresses MVC from raising exception
                filterContext.ExceptionHandled = true;
            }
        }
    }

此筛选器应用于此控制器操作方法:

   [ArgumentExceptionFilter]
   public ActionResult MyActionMethod(SettingsRoot settings)
   {
     ActionResult actionResult = null;
     //Do stuff with settings
     return actionResult;
   }

我希望调用"MyActionMethod()",无论我们是否收到触发异常过滤器的异常。我也尝试使用"重定向到路由结果()"方法,但没有奏效。有什么建议吗?

如何允许自定义异常筛选器在异常期间继续调用指定的操作方法

可以使用 filterContext 的 Result 属性重定向到具有默认参数的控制器操作。

    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() == typeof(System.ArgumentException))
        {
            //This simply surpresses MVC from raising exception
            filterContext.ExceptionHandled = true;
            //Some logic to create a default "SettingsRoot" parameter
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "Default" },
                { "action", "MyActionMethod" },
                { "settings", new SettingsRoot() }
            });
        }
    }