net mvc添加全局异常处理

备忘,记录一下

添加一个异常过滤器

public class MyHandleErrorAttribute: HandleErrorAttribute
{

public override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;

string strController = filterContext.RouteData.Values["controller"].ToString();
string strAction = filterContext.RouteData.Values["action"].ToString();
Common.Log4netHelper.Error("/"+ strController + "/"+ strAction);
Common.Log4netHelper.Error(ex);
filterContext.Result = new RedirectResult("~/error.html");

filterContext.ExceptionHandled = true;

base.OnException(filterContext);
}

}

App_Start里建立FilterConfig

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//添加全局过滤器
filters.Add(new Filter.MyAuthorizeAttribute());
filters.Add(new Filter.MyHandleErrorAttribute());
}
}

Global.asax里注册FilterConfig

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

posted @ 2021-05-25 15:19  奇迹之耀  阅读(79)  评论(0编辑  收藏  举报