How to use Exception filters in MVC 5

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

    You could derive your own HandleErrorAttribute

    public class NLogExceptionHandlerAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            // log error to NLog
            base.OnException(filterContext);
        }
    }
    

    Then register it globally

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new NLogExceptionHandlerAttribute());
        ...
    }
    

    By default, the HandleErrorAttribute will display the Error view located in the ~/Views/Shared folder but if you wanted to display a specific view you can set the View property of the attribute.

提交回复
热议问题