且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 MVC 5 中使用异常过滤器

更新时间:2023-02-24 12:33:46

您可以派生自己的 处理错误属性

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

然后全局注册

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

默认情况下,HandleErrorAttribute 将显示位于 ~/Views/Shared 文件夹中的 Error 视图,但如果您想显示一个具体视图可以设置View属性的属性.

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.