在Asp.Net的Global.asax中Application_Error跳轉到自定義錯誤頁無效的解決辦法

在開發Asp.Net系統的時候,咱們不少時候但願系統發生錯誤後可以跳轉到一個自定義的錯誤頁面,因而咱們常常會在Global.asax中的Application_Error方法中使用Response.Redirect方法跳轉到自定義錯誤頁,但有時候(特別是當站點部署到IIS後)Application_Error方法中使用Response.Redirect方法會失效,當Asp.Net發生異常錯誤後仍是顯示出來的是Asp.Net的默認錯誤黃頁。其根本緣由是儘管咱們在Application_Error方法中使用了Response.Redirect方法,可是當系統發生異常錯誤後Asp.Net認爲異常並無被處理,因此Asp.Net不會跳轉到Application_Error方法中Response.Redirect指向的頁面,仍是會最終會跳轉到Asp.Net的默認錯誤黃頁。解決這個問題的辦法很簡單就是在Application_Error方法中使用Response.Redirect作跳轉前,先調用Server.ClearError()方法告訴Asp.Net系統發生的異常錯誤已經被處理了,這樣再調用Response.Redirect方法系統就會跳轉到自定義錯誤頁面了。html

 

下面是一段示例代碼:app

 1 using System;
 2 using System.Web;
 3 using System.Web.Mvc;
 4 using System.Web.Routing;
 5 using System.Web.Http;
 6 
 7 namespace RedirectToErrorPage
 8 {
 9     public class Global : HttpApplication
10     {
11         void Application_Start(object sender, EventArgs e)
12         {
13             // Code that runs on application startup
14             AreaRegistration.RegisterAllAreas();
15             GlobalConfiguration.Configure(WebApiConfig.Register);
16             RouteConfig.RegisterRoutes(RouteTable.Routes);            
17         }
18 
19         //儘管咱們在Global.asax的Application_Error方法中使用了Response.Redirect方法作頁面重定向,可是當系統發生錯誤時Asp.Net認爲錯誤沒有被處理,因此最後頁面仍是會被重定向到Asp.Net的默認錯誤黃頁,而不會跳轉到咱們在Application_Error方法中用Response.Redirect指向的頁面。
20         protected void Application_Error(object sender, EventArgs e)
21         {
22             Server.ClearError();//在Global.asax中調用Server.ClearError方法至關因而告訴Asp.Net系統拋出的異常已經被處理過了,不須要系統跳轉到Asp.Net的錯誤黃頁了。若是想在Global.asax外調用ClearError方法能夠使用HttpContext.Current.ApplicationInstance.Server.ClearError()。
23             Response.Redirect("~/ErrorPage.html", true);//調用Server.ClearError方法後再調用Response.Redirect就能夠成功跳轉到自定義錯誤頁面了
24         }
25 }
相關文章
相關標籤/搜索