码迷,mamicode.com
首页 > Web开发 > 详细

【MVC__ExceptionFilter】全局异常处理

时间:2020-05-01 01:31:28      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:通过   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!