2 June, 2010
0 Comments
1 category
If you want to use a custom error page in ASP .NET and want to show the exception details on that page, you must save the Server.GetLastError to a sessions variable in the Global.asax Application_Error event, manually clear the error and than manually redirect to a ErrorPage.aspx and do not use the Web.config “customErrors” tag.
Global.asax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace CustomBeheer { public class Global : System.Web.HttpApplication { /// <summary> /// Code that runs when an unhandled error occurs /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Application_Error(object sender, EventArgs e) { // Catch exception and save to session variable, for displaying in ErrorPage.aspx Exception ex = Server.GetLastError(); try { // Session object is not always available, so use try finally block. // This will prevent recursive loop. Session["EncounteredException"] = ex; } finally { // To use the Session variable in ErrorPage.aspx we must clear the error and then manualy redirect to the ErrorPage.aspx. // Because we manualy redirect, we don't use the "customErrors" tag in the Web.config Server.ClearError(); Response.Redirect("ErrorPage.aspx"); } } } }
ErrorPage.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Beheer { public partial class ErrorPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Exception ex = Server.GetLastError(); this.ShowError(); } private void ShowError() { Exception encounteredException = Session["EncounteredException"] as Exception; if (encounteredException != null) { Session["EncounteredException"] = null; lblError.Text = encounteredException.ToString(); } } } }
[No changes to the Web.config]
Result
The text: “Oops… something bad happened” is a predefined text and the “System.Web.HttpUnhandledException…” shows the exception details, catched in the global.asax Application_Error event.
More on CustomErrorPages
http://aspnetresources.com/articles/CustomErrorPages.aspx
Tags: ASP .NET
Category: Uncategorized