通过实现接口IExceptionFilter
Global文件添加GlobalFilters.Filters.Add(new ExExceptionFilter());
public class ExExceptionFilter : IExceptionFilter
{
private static ILog log = LogManager.GetLogger(typeof(ExExceptionFilter));
public void OnException(ExceptionContext filterContext)
{
log.Error("出现未处理异常", filterContext.Exception);
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
if (request.Headers.AllKeys.Contains("X-Requested-With") && request.Headers["X-Requested-With"].Equals("XMLHttpRequest"))
{
AjaxResult ajaxResult = new AjaxResult(0, "发生错误");
ajaxResult.data.Add("Exception", filterContext.Exception.Message);
ajaxResult.data.Add("detail", filterContext.Exception.ToString());
filterContext.Result = new JsonResult() { Data = ajaxResult };
}
else
{
filterContext.Result = new RedirectResult("/Manager/Manager/Error");
}
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
//filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}