在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方法系统就会跳转到自定义错误页面了。

下面是一段示例代码:

 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 }
原文地址:https://www.cnblogs.com/OpenCoder/p/5070645.html