How to use Exception filters in MVC 5

前端 未结 4 780
没有蜡笔的小新
没有蜡笔的小新 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:06

    Below worked for me. A few things to note 1) RedirectResult points to a controller action, not a view 2) you need to set filterContext.ExceptionHandled = true; or your exception view / page will not display.

    public class ErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            Log.Logger.Error(filterContext.Exception, "An Unhandled exeption occured durring the execution of a request");
    
            filterContext.Result = new RedirectResult("~/MyControler/MyErrorAction");
            filterContext.ExceptionHandled = true;
        }
    
    }
    

    Ofcourse you will also need to register the Error attribute using the GlobalFilters object from your Global.asax as shown below.

     protected void Application_Start()
     {
         GlobalFilters.Filters.Add(new ErrorAttribute());           
         ...
     }
    

提交回复
热议问题