0

What I am trying to do is that I have used a function in the Global.asax.cs file to detect when a user's login session has expired and if it is expired then the user should be redirected to the login page, code shown below:

protected void Session_Start(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                       //I want to let the client side page to pop-up an alert to indicate the user 
                       //that the session is expired.

                        Response.Write("<script>alert('Your Session is out, please re-login!');</script>");

                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

However, the issue for my current code is that when the session expired, the page will be redirected directly, there is no pop up of alert at all.

Could someone help? Thanks in advance!

  • You're not understanding how HTTP works. A redirect command tells the browser to ignore anything in the response to the current request, and go to a completely new URL instead. Your Javascript is returned to the browser, but it ignores it - because you told it to with the Redirect command - and goes straight to the login page instead. Personally I actually think that's fine from a UX perspective, most users will be used to the fact that sites occasionally require them to log in again. So I'm not sure you really need the message anyway. – ADyson Sep 18 '20 at 14:35
  • @ADyson Sir, thank you for your quick respond. And yes I am getting this is an ugly move with JS. Will it be possible to do like redirecting user first to re-login then pop-up an alert/confirm on the login page? – Jonathangagaga Sep 18 '20 at 14:43
  • You could - you'd have to put some querystring parameter into the login page URL telling it that the visit is due to an expired session, so it knows to show the alert. Or you could remove the Response.Redirect here, and put `window.location = "Login.aspx";` into the JS just after the alert, so it does a client-side navigation to the login page. (But you also need to ensure in the C# that the response is ended after this, so that no other data gets displayed by accident). But yes, it's an ugly solution and probably not necessary, either way. JS alerts are intrusive and a bit retro. – ADyson Sep 18 '20 at 14:45
  • @ADyson Thank you for your suggestion and time, really appreciate that! – Jonathangagaga Sep 18 '20 at 15:18

0 Answers0