Error pages in ASP.NET

In ASP.NET you can retrieve the last unhandled exception via:

(HttpContext.Current.)Server.GetLastError() // Server object is available as a property in Page and UserControl context

This obviously only works in the same roundtrip. If you want to retrieve this information in your error page, you got a problem because the error page is not returned in the same roundtrip. The server responds with a redirect response and a new request to the error page is automatically sent. A common workaround would be to store the exception in your Session state from the Application_Error event in Global.asax.

From ASP.NET 3.5 you can configure the redirect mode for error pages:

<customErrors mode="On" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite" />

This way the redirect response is not sent and the error page is returned right away. That implies that the browser is not aware of a page change and cannot reflect it in the address bar, so your original URL is not replaced with the URL of the error page, which might be what you actually want…


  • Have you tried putting something into Session in application_error? I don't believe it works, I tried it and although it had no exceptions the value was not available later at a different page.

  • Sure it worked for me in the past. By default, you should be able to store any object in the session state. It is not serialized.

    There should be another reason why the session state doesn't work for you. Probably wrongly configured or disabled at some point. Also make sure your Session is not abandoned between the time of storing the exception and retrieving it...

Comments have been disabled for this content.