asp.net mvc中配置全局异常过滤器

第一步:定义一个类:SysHandlerErrorAttribute 继承HandleErrorAttribute

重写OnException方法

using Dw.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LoanH5_2020.Models
{
    public class SysHandlerErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //1.获取异常对象
            Exception ex = filterContext.Exception;
            //2.获取请求的类名和方法名
            string strController = filterContext.RouteData.Values["controller"].ToString();
            string strAction = filterContext.RouteData.Values["action"].ToString();
            //3.记录异常日志
            string errMsg = String.Format("控制器:{0};Action:{1};异常信息:{2};", strController, strAction, ex.ToString());
            NLogHelp.WriteInfo(errMsg);
            NLogHelp.WriteDebug(errMsg);
            //重定向到友好页面
            filterContext.Result = new RedirectResult("/Error/Index");
            //标记异常已经处理完毕
            filterContext.ExceptionHandled = true;
            base.OnException(filterContext);
        }
    }
}

第二步 在 filterConfig中添加自定义的SysHandlerErrorAttribute

using LoanH5_2020.Models;
using System.Web;
using System.Web.Mvc;

namespace LoanH5_2020
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new SysHandlerErrorAttribute());
        }
    }
}

第三步,在Web.config中配置system.web节点下

 <customErrors mode="On"></customErrors>

 

posted @ 2020-11-05 15:40  代码沉思者  阅读(420)  评论(0编辑  收藏  举报