簡體   English   中英

如何允許自定義ExceptionFilter在異常期間繼續調用指定的Action方法

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

當我的異常過濾器被調用時,我希望控制器中的預期動作仍然被調用。 我創建了以下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()”被調用,無論我們是否得到觸發ExceptionFilter的異常。 我也嘗試使用“ RedirectToRouteResult()”方法,但是沒有用。 有什么建議么?

您可以使用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