Session cleared when using customErrors

Today I was totally amazed at this finding: your session is cleared when you use a <customErrors> section in the web.config of your ASP.NET web application.

Here’s the setting:

Inside your page’s Page_Error eventhandler or Global_Error (aka Application_Error) eventhandler you have this bit of exception handling code:

Exception ex = Server.GetLastError();
Session[“Exception“] = ex;

You do not call Server.ClearError(), in order to let the exception escalate, so it is picked up by the ASP.NET fallback mechanism. This will read the web.config section and use whatever is inside the <customErrors> section. Let’s say it looks like this:

<customErrors defaultRedirect=“Error.aspx“ mode=“On“>
  <error statusCode=“500“ redirect=“Error.aspx“ />

Normally, you wouldn’t need the defaultRedirect AND the error for statuscode 500, but this is just to be sure.

Inside the Error.aspx you access your Session and… presto!! Session is empty. The “All your session are belong to us“ virus has struck.

Upon closer inspection, you will see that your SessionID is still the same. All entries from the session have been deleted. Now, is it just me, or is this plain stupid? If a catch my exception through this mechanism, I do not want my users to lose all of their session variables.

An easy workaround is to add the following lines to your _Error function:


However, this means that you hardcode the error page Url. You could make this an appSetting. It also means that you would always redirect to the error page. No fancy distinction between local and remote clients, such as the remoteOnly mode of the custom errors. This would not be too difficult to implement, but hey, wasn’t that what the customErrors mechanism was all about?

I found only one reference of this problem on the usual forums.

Anybody have any ideas? I would appreciate your thoughts on this.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s