FeliceM
FeliceM

Reputation: 4199

Prompt user and redirect if session is expired

I have a button in one page that opens up a window with inside an exchange rate calculator. The exchange rate calculator is a an external web service. Can happen that the session is expired but the user is still on the page and clicking on the button that open such window, instead of the calculator, the web site login page appears. To avoid the user to login from the page in the window, I am trying to check if the session is still existing and if not prompt the user that the session is expired and he needs to login again. To avoid that despite the warning the user still try to login from the window, I would like to stop the page in the window to load and redirect to the login page when the user click ok in the prompt button.

public void Page_Init(object o, EventArgs e)
{
    if (Session ["isUser"] != "isUser")
    {

        ScriptManager.RegisterStartupScript(
        this,
        this.GetType(),
        "Warning",
        "alert('Your session expired! You shall login again.');",
        true);
        Response.Redirect("~/Login.aspx");
    }
}

The above method sometimes shows the prompt sometimes it doesn't and in any case newer reach the last line to redirect to the login page. I need some help to get the above scenario under control. How can I make the above logic working? I mean get the prompt displayed if the condition is not meet, the page not loading and redirect on the ok of the user?

Upvotes: 0

Views: 3677

Answers (3)

saurav
saurav

Reputation: 1002

You can try this code which uses WebMethod to invalidate current login session cookie then alerts user about session expiration and then redirects user to the login page.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    <script type="text/javascript">
    var HeartBeatTimer;


    function StartHeartBeat()
    {
        if (HeartBeatTimer == null) {
            //timouts after 1 minute
            HeartBeatTimer = setInterval("HeartBeat()", 1000 * 60*1);
        }
    }

    function HeartBeat()
    {
        PageMethods.PokePage(onSucess, onError);
        function onSucess(result) {
            alert('Session Expired');
            window.location = result;
        }
        function onError(result) {
            alert('Something wrong.');
        }
    }
    </script>
    </head>
    <body   onload="StartHeartBeat();">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
    <div>

    </div>
    </form>
    </body>
    </html>

And the C# code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebApplication1
    {
    public partial class WebForm1 : System.Web.UI.Page
    {
    static int x = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie hc = new HttpCookie("kk", "kk");
        hc.Expires = DateTime.Now.AddMinutes(5);
        Response.Cookies.Add(hc);
    }
    [WebMethod(EnableSession = true)]
    public static String PokePage()
    {
        HttpCookie hc = new HttpCookie("kk", "kk");
        hc.Expires = DateTime.Now.AddMinutes(-5);
        HttpContext.Current.Response.Cookies.Add(hc);
        return "http://www.google.com";
    }
    }
    }

Upvotes: 0

FeliceM
FeliceM

Reputation: 4199

I finally found the way to solve the problem. To avoid a never ending loop trying to redirect from the window I need to close, I did it from the javascript function used to open the window. So basically before I open the window I check if the session is valid and if not I redirect before opening it.

function openRadWin() {

   var session='<%= Session["isUser"]%>';
   if (session != "isUser") {
   alert("Your Session has expired. Click OK to login again.");
   window.location = "../Login.aspx";
   }

   else {
   var width = "430px";
   var height = "355px";
   var left = "800px";
   var top = "150px";
   radopen("currencies.aspx", "RadWindow1", width, height, left, top);
    }
   }

Thanks to Wizpert for some good suggestion but I decided to minimize the code and to do all in few lines.

Upvotes: 1

Adam
Adam

Reputation: 3914

I just implemented this in my project, and it works live and fine now :

1) implement a class that handle your session

 public static class SessionManager
    {


        public static object _Session_UserInfo
        {

            get
            {

                if (HttpContext.Current.Session["isUser"] == null)
                {
                    HttpContext.Current.Response.Redirect("Index?Expired=1");
                    return null;
                }

                else
                {
                    return HttpContext.Current.Session["isUser"];
                }
            }


            set
            {
                HttpContext.Current.Session["isUser"] = value;


            }

        }



    }

//2) start referencing the sesison variable from this calss:

public void Page_Init(object o, EventArgs e)
{
     //do whatever you wanna do with it, it will automatically redirect if expired
     //SessionManager._Session_UserInfo;


}

//in javascript do the following :

function getParameterByName(n) {
            var half = location.search.split(n + '=')[1];
            return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
        }

        $(document).ready(function () {

            var _IsSessionExpired = getParameterByName("Expired");
          //  alert(_IsSessionExpired);
            if (_IsSessionExpired != null)
                alert('Your Session Has Expired, please login to the system !');
                      window.location="any page you want to redirect to";

        });

your welcome

Upvotes: 1

Related Questions