Response.redirect in Session_Start not working

I have a simple code Session_Startthat 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 on my site whenever it is called Response.Redirect(), it also completes the code. If here, even if the page is ultimately redirected, a line is also executed dim dummy=4/0.

This causes problems in other code called from Session_Start()where I built on the assumption that the redirect is the exit point.

I also tried setting endResponsein an overloaded method Response.Redirect(url, endResponse)like trueor false, but this does not work either.

+5
source share
3 answers

Having studied the source code of the framework, I can explain why it Response.Redirect(url, true)continues to execute the code after calling in Session_Start(), but not in the normal code behind.

Response.Redirect()ultimately calls an internal overloaded method Redirect():

internal void Redirect(string url, bool endResponse, bool permanent)
{
  // Miscellaneous goings on

  if (endResponse)
  {
    this.End();
  }
}

At the end of this method, if endResponsetrue, is called Response.End(). When we look at Response.End(), we see the following code:

public void End()
{
    if (this._context.IsInCancellablePeriod)
    {
        InternalSecurityPermissions.ControlThread.Assert();
        Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
    }
    else if (!this._flushing)
    {
        this.Flush();
        this._ended = true;
        if (this._context.ApplicationInstance != null)
        {
            this._context.ApplicationInstance.CompleteRequest();
        }
    }
}

The method checks the status of the current context value IsInCancellablePeriod. 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 of the IsInCancellablePeriodinvisible member, we will see:

enter image description here

, , Response.Redirect() , endResponse .

ASPX- Page_Load(), - :

enter image description here

IsInCancellablePeriod true, Thread.CurrentThread.Abort(), Response.Redirect() .

, , :

Session ( )

Response.Redirect() Session_Start(), If...Then...Else:

If <some_condition_we_have_to_redirect_for> Then
    Response.Redirect("~/Blog.aspx")
Else
    // Normal session start code goes here
End If
+11

,.Redirect , senarios, HttpContext.Current.Response.End() , .

0

http://msdn.microsoft.com/en-us/library/a8wa7sdt%28v=vs.80%29.aspx

public void Redirect (
    string url,
    bool endResponse
)
  • url is the target location.
  • endResponse - Indicates whether to terminate the current page.
-1
source

All Articles