简体   繁体   English

如何允许自定义ExceptionFilter在异常期间继续调用指定的Action方法

[英]How to allow custom ExceptionFilter to continue to call the designated Action Method during exceptions

When my Exception Filter is called, I'd like the intended action within my controller to still be called. 当我的异常过滤器被调用时,我希望控制器中的预期动作仍然被调用。 I had created the following IExceptionFilter: 我创建了以下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;
            }
        }
    }

and this filter is applied to this controller action method: 并将此过滤器应用于此控制器操作方法:

   [ArgumentExceptionFilter]
   public ActionResult MyActionMethod(SettingsRoot settings)
   {
     ActionResult actionResult = null;

     //Do stuff with settings

     return actionResult;
   }

I would like to have "MyActionMethod()" to be called regardless if we get an exception that triggers the ExceptionFilter. 我希望有“ MyActionMethod()”被调用,无论我们是否得到触发ExceptionFilter的异常。 I also tried to use "RedirectToRouteResult()" approach but that didn't work. 我也尝试使用“ RedirectToRouteResult()”方法,但是没有用。 Any suggestions? 有什么建议么?

You can use the Result property of the filterContext to redirect to your controller action with a default parameter. 您可以使用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() }
            });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM