ASP.NET MVC 异常记录

新建一个类继承自 HandleErrorAttribute,然后重写OnException这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public class LogHandleErrorAttribute: HandleErrorAttribute
{
private readonly ILoggerService _log;

public LogHandleErrorAttribute(ILoggerService log)
{
this._log = log;
}
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
_log.Error("被系统过滤捕获的异常" + filterContext.Exception.ToString());
filterContext.HttpContext.Response.Redirect("/");
}
}

只要程序出错就会执行这个方法。