1.配置文件中开启CustomErrors
<customErrors mode="On" defaultRedirect="~/Home/Error">
<error statusCode="404" redirect="~/Home/NotFound" />
</customErrors>
2.新建一个MyExceptionFilter类,实现IExceptionFilter接口
public class MyExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
Exception ex = context.Exception;
if (!(ex is HttpException))
{
// 记录日志
}
}
}
3.注册过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyExceptionFilter()); // 一定要放在 HandleErrorAttribute 之前
filters.Add(new HandleErrorAttribute()); // 这里拦截了Error消息,所以Application_Erro不会触发
}