Response.Redirect() doesn't work

BumbleBee picture BumbleBee · Aug 12, 2011 · Viewed 11.3k times · Source

I have Default.aspx page, which inherits from BasePage.cs, which inherits from System.Web.UI.Page. BasePage is where I check if the session has timed out. When the session has timed out and the user clicks on something, I need to redirect the user back to the "Main.aspx" page.

Here is the code in my Basepage

 override protected void OnInit(EventArgs e)
{
  base.OnInit(e);
  if (Context.Session != null)
    {
        if (Session.IsNewSession)
        {
            string cookie = Request.Headers["Cookie"];
            if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
            {
                HttpContext.Current.Response.Redirect("Main.aspx", true);
                return;
            }
        }
    }
}

HttpContext.Current.Response.Redirect("Main.aspx", true);

I want the redirect to stop execution of BasePage and immediately jump out. The problem is, it doesn't.

When I run in debug mode, it contines stepping through as though it didn't just redirect and leave. How can I safely redirect?

Answer

James Johnson picture James Johnson · Aug 12, 2011

Seeing that your base class is inheriting from System.Web.UI.Page, you don't need to use HttpContext. Try it without and see if it helps.

EDIT: Added page check around response.redirect

if (!Request.Url.AbsolutePath.ToLower().Contains("main.aspx"))
{
    Response.Redirect("<URL>", false);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}