How to use Exception filters in MVC 5

前端 未结 4 782
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 08:57

How i can implement Exception Filters in MVC5.

I want to throw the exception to NLog and redirect the page to a default error page which displays \"Something is gone

4条回答
  •  不知归路
    2021-01-04 09:13

    Exception filters are run only when unhandled exception has been thrown inside an action method. As you asked, here is an example to redirect to another page upon exception:

    public class MyExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if(!filterContext.ExceptionHandled)
            {
                filterContext.Result = new RedirectResult("~/Content/ErrorPage.html");
                filterContext.ExceptionHandled = true;
            }    
        }
    }
    

    Now, to apply this filter to either controllers or individual actions, put [MyException] on them.

    You may need to check the occurence of an specific Exception inside the if clause. e.g.:

    if(... && filterContext.Excaption is ArgumentOutOfRangeException)
    

    To return a View as Exception Response:

    filterContext.Result = new RedirectResult("/Home/ErrorAction");
    

    other alternatives you might use to redirect are:

    • new RedirectToRouteResult{ ... }
    • new ViewResult{ ... }

提交回复
热议问题