【MVC】 异常处理
一 . 自定义 HandleErrorAttribute
public class ExceptionLogAttribute : HandleErrorAttribute
{
/// <summary>
/// 触发异常时调用的方法
/// </summary>
/// <param name="filterContext"></param>
public override void OnException(ExceptionContext filterContext)
{
Log(filterContext);
filterContext.Result = new RedirectResult("/Error/Index");
base.OnException(filterContext);
}
} public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ExceptionLogAttribute());
filters.Add(new HandleErrorAttribute());
}
}
二. 重写 Controller OnException 函数
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
Log(filterContext);
filterContext.Result = new RedirectResult("/Error/Index");
}
}