【MVC__ExceptionFilter】全局异常处理

2021-03-14 08:35

阅读:695

标签:通过   ror   global   and   head   TBase   redirect   sharp   ilog   

通过实现接口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;
        }
    }

【MVC__ExceptionFilter】全局异常处理

标签:通过   ror   global   and   head   TBase   redirect   sharp   ilog   

原文地址:https://www.cnblogs.com/kikyoqiang/p/12812188.html


评论


亲,登录后才可以留言!