Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.Redirect() doesn't work

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?

like image 988
BumbleBee Avatar asked Aug 12 '11 18:08

BumbleBee


People also ask

How do I use response redirect?

Response. Redirect sends an HTTP request to the browser, then the browser sends that request to the web server, then the web server delivers a response to the web browser. For example, suppose you are on the web page "UserRegister. aspx" page and it has a button that redirects you to the "UserDetail.

What can I use instead of a response redirect?

For instance, instead of a "form" button that causes a postback and redirect, you could use a LinkButton that will behave like a hyperlink, allowing the browser to request the new page directly.

Does response redirect stop execution?

When you use Response. Redirect("Default. aspx",true ) which is by default true then the execution of current page is terminated and code written after the Response. Redirect is not executed instead of executing code written after the Response.

Does response redirect clear session?

The session is cleared because the cookie tracking the session is lost, since you are crossing domains. So yes - it's by design.


2 Answers

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();
}
like image 175
James Johnson Avatar answered Oct 18 '22 00:10

James Johnson


I don't think it's exactly what you are looking for but maybe this would work:

Server.Transfer("<URL>")
like image 35
Jeremy Bade Avatar answered Oct 17 '22 23:10

Jeremy Bade