asp.net mvc HandleErrorAttribute 異常錯誤處理 無效!


系統未知bug,代碼沒有深究。 

現象:filters.Add(new HandleErrorAttribute()); 使用了全局的異常處理過濾。

HandleErrorAttribute 核心代碼:

public virtual void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }
            Exception exception = filterContext.Exception;
            if (new HttpException(null, exception).GetHttpCode() != 500)
            {
                return;
            }
            if (!this.ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            filterContext.Result = new ViewResult
            {
                ViewName = this.View,
                MasterName = this.Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
View Code

 經過測試,下面這些代碼執行完成之后,頁面還是顯示黃頁黃頁。而不是系統 默認的Error視圖

web.config中配置:customErrors mode="RemoteOnly"

 filterContext.ExceptionHandled = true;
 filterContext.HttpContext.Response.Clear();
 filterContext.HttpContext.Response.StatusCode = 500;
 filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

有一個項目情況一定是這樣的,其他好幾個項目正常。

修復代碼如下,使用自定義類繼承自HandleErrorAttribute  重寫方法OnException

加入代碼

base.OnException(filterContext);
if (filterContext.ExceptionHandled)
filterContext.HttpContext.ClearError();

關鍵代碼:filterContext.HttpContext.ClearError().

具體原因不明,還有待查證,那位大哥有碰到過??? 猜測可能和httpcontext最后執行的邏輯判斷有問題,比如config的配置,運行時參數的不一致等

 

回家查看asp.net的源代碼去,找找ExceptionHandled預計能找到點東西


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM