asp.net on session timeout redirect to home page

2019-04-16 03:55发布

问题:

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

回答1:

Why don't you use JavaScript to do it? you can use setTimeout method like

<script type="text/javascript">
setTimeout('window.location = "home.aspx"', 3000);
</script>

Put the above js code block into the page header which 3000 is your session timeout.



回答2:

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");
                    }
                }
            }
        }
    }