Clearing Session in Global Application_Error
Whenever an unhandled exception occurs on our site, I want to:
- Send a notification email
- Clear the user's session
- Send the user to a error page ("Sorry, a problem occurred...")
The first and last I've had working for a long time but the second is causing me some issues. My Global.asax.vb includes:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Send exception report
Dim ex As System.Exception = Nothing
If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Server IsNot Nothing Then
ex = HttpContext.Current.Server.GetLastError
End If
Dim eh As New ErrorHandling(ex)
eh.SendError()
' Clear session
If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.Session IsNot Nothing Then
开发者_StackOverflow社区 HttpContext.Current.Session.Clear()
End If
' User will now be sent to the 500 error page (by the CustomError setting in web.config)
End Sub
When I run a debug, I can see the session being cleared, but then on the next page the session is back again!
I eventually found a reference that suggests that changes to session will not be saved unless Server.ClearError is called. Unfortunately, if I add this (just below the line that sets "ex") then the CustomErrors redirect doesn't seem to kick in and I'm left with a blank page?
Is there a way around this?
Brunis - In answer to your question (I had the same problem) your application may have crashed out to application_error at a point before you have access to the session information, such as Begin_Request stage.
Can you clear the session on your custom error page?
Also, you might want to look into using ELMAH. It makes all the stuff you are trying to do easy and awesome.
精彩评论