asp.net on session timeout redirect to home page

Yogesh picture Yogesh · Apr 9, 2011 · Viewed 7.9k times · Source

i have web app and on session timeout and user interaction on the page, this needs to redirect to home/landing page

solutions found on the net

1) Session check in page_load of all the aspx pages of the application. 2) code in session start of global.asax

public void Session_Start    
{
        Response.Redirect("home.aspx");
        // or Server.Transfer("home.aspx");
}

I am going for 2nd option,let me know 1) whether i am in right way or any better solutions for this? 2) in the second option whether to use Response.Redirect or Server.Transfer

-Thanks

Answer

Pranay Rana picture Pranay Rana · Jun 2, 2011

I will go for the first one and do check for the session.....

Write following code in OnInit method of the Master page will do your tack easily

    /// <summary>
    /// Check for the session time out 
    /// </summary>
    /// <param name="e"></param>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Context.Session != null)
        {
            //check whether a new session was generated
            if (Session.IsNewSession)
            {
                //check whether a cookies had already been associated with this request
                HttpCookie sessionCookie = Request.Cookies["ASP.NET_SessionId"];
                if (sessionCookie != null)
                {
                    string sessionValue = sessionCookie.Value;
                    if (!string.IsNullOrEmpty(sessionValue))
                    {
                        // we have session timeout condition!
                        Response.Redirect("Home.aps");
                    }
                }
            }
        }
    }