I have a simple Session_Start code that looks like this:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim sid = Session.SessionID
Response.Redirect("~/Blog.aspx")
dim dummy=4/0
End Sub
It does not work as expected. Usually in my whole site, whenever Response.Redirect() is called, it also terminates the code execution. Whereas here, even if the page eventually redirects, the dim dummy=4/0 line is also executed.
This is causing me problems in other code called from Session_Start() where I built on the assumption that the redirect is an exit point.
I also tried setting endResponse in the Response.Redirect(url, endResponse) overloaded method as true or false but this doesn’t work either.
Having had a dig into the framework source code I can explain why
Response.Redirect(url, true)continues to execute code after being called inSession_Start()but not in regular code behind.Response.Redirect()ultimately calls an internal overloaded method ofRedirect():At the end of this method, if
endResponseis true thenResponse.End()is called. When we look atResponse.End()we see the following code:The method examines the state of the current context’s
IsInCancellablePeriodvalue. This value is internal but we can see it in our debugger:If we set a breakpoint inside
Session_Start()and examine the current context’sIsInCancellablePeriodnon-visible member we see:This means that the request’s thread won’t be aborted and so the code after
Response.Redirect()will execute, regardless of whether you setendResponseor not.If we set a breakpoint inside an ASPX page’s
Page_Load()event we see something different:The current context’s
IsInCancellablePeriodnon-visible member is set to true and soThread.CurrentThread.Abort()will be called and no more code will execute after theResponse.Redirect().The reason for this difference in behaviour is I suspect to do with protecting your session state integrity:
If you need to prevent code from executing after a
Response.Redirect()inSession_Start()then you’ll need to use anIf...Then...Else: