How can I redirect to a page when the user session expires?

前端 未结 11 1712
我在风中等你
我在风中等你 2020-12-28 20:25

I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. T

相关标签:
11条回答
  • 2020-12-28 20:59

    You can handle this in global.asax in the Session_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired:

       public void Session_OnStart()
        {
            if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null)
            {
                HttpContext.Current.Response.Redirect("SessionTimeout.aspx")
            }
    
        }
    

    Alas I have not found any elegant way of finding out the name of the session cookie.

    0 讨论(0)
  • 2020-12-28 20:59

    Are you putting something in the Session object that should always be there? In other words, if they log in, you may be putting something like UserID in the session

    Session("UserID") = 1234
    

    So, if that is the case, then you could add something to your codebehind in the master page that checks for that value. Something like this:

    Dim UserID As Integer = 0
    Integer.TryParse(Session("UserID"), UserID)
    
    If UserID = 0 Then
      Response.Redirect("/sessionExpired.aspx")
    End If
    
    0 讨论(0)
  • 2020-12-28 20:59

    Are you looking to redirect on the next request, or redirect immediately, without user intervention? If you're looking to redirect without user intervention, then you can use ClientScript.RegisterStartupScript on your Master Page to inject a bit of javascript that will redirect your clients when their session expires.

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        String timeoutPage = "SessionExpired.aspx"; // your page here
        int timeoutPeriod = Session.Timeout * 60 * 1000;
    
        sb.AppendFormat("setTimeout(\"location.href = {0};\",{1});", timeoutPage, timeoutPeriod);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "timeourRedirect", sb.ToString(), true);
    
    0 讨论(0)
  • 2020-12-28 21:03

    You can also check the solutions provided in below link

    Detecting Session Timeout And Redirect To Login Page In ASP.NET

    0 讨论(0)
  • 2020-12-28 21:04

    The other way is to tell the browser to redirect itself (via javascript) after a certain amount of time... but that can always be deactivated by the user.

    0 讨论(0)
提交回复
热议问题