public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SysExceptionAttribute());
}
}
public class SysExceptionAttribute : HandleErrorAttribute
{
protected ILog log = LogManager.GetLogger(typeof(SysExceptionAttribute));
public override void OnException(ExceptionContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
string msg = filterContext.Exception.Message;
string stackTrace = filterContext.Exception.StackTrace;
string clientIP = Common.UntilHelper.GetClientIp();
log.Error("Ajax:" + filterContext.HttpContext.Request.IsAjaxRequest() + ";IP地址:" + clientIP + ";访问路由:" + controller + "/" + action + ";URL:" + filterContext.HttpContext.Request.RawUrl + ";Message:" + msg + ";StackTrace:" + stackTrace);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.Write("error");
}
else
{
filterContext.HttpContext.Response.Redirect("/common/error");
}
filterContext.HttpContext.Response.End();
}
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SysExceptionAttribute());
}
}
public class SysExceptionAttribute : HandleErrorAttribute
{
protected ILog log = LogManager.GetLogger(typeof(SysExceptionAttribute));
public override void OnException(ExceptionContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
string msg = filterContext.Exception.Message;
string stackTrace = filterContext.Exception.StackTrace;
string clientIP = Common.UntilHelper.GetClientIp();
log.Error("Ajax:" + filterContext.HttpContext.Request.IsAjaxRequest() + ";IP地址:" + clientIP + ";访问路由:" + controller + "/" + action + ";URL:" + filterContext.HttpContext.Request.RawUrl + ";Message:" + msg + ";StackTrace:" + stackTrace);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.Write("error");
}
else
{
filterContext.HttpContext.Response.Redirect("/common/error");
}
filterContext.HttpContext.Response.End();
}
}
在Global.asax中加入:
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
也可以写到
protected void Application_Error(object sender, EventArgs e){}