ASP.NET Push Redirect on Session Timeout

前端 未结 10 1870
Happy的楠姐
Happy的楠姐 2020-11-29 21:04

I\'m looking for a tutorial, blog entry, or some help on the technique behind websites that automatically push users (ie without a postback) when the session expires. Any h

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 21:57

    Well this gets tricky for AJAX requests as Zhaph - Ben Duguid pointed out. Here was my solution to make this work with AJAX (using Telerik web controls but they are built using ASP.NET AJAX toolkit I believe).

    In a nutshell, I rolled my own sliding expiration session type thing.

    In my Site.Master, I am updating a session variable on EVERY postback (postback or AJAX request because AJAX requests still kick off the Page_Load event):

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (this.Request.IsAuthenticated)
                    this.pnlSessionKeepAlive.Visible = true;
                else
                    this.pnlSessionKeepAlive.Visible = false;
            }
    
            if (this.Session["SessionStartDateTime"] != null)
                this.Session["SessionStartDateTime"] = DateTime.Now;
            else
                this.Session.Add("SessionStartDateTime", DateTime.Now);
        }
    

    Then in my markup for my site.master, I included an iframe with a ASPX page I use "behind the scenes" to check and see if my custom sliding expiration has expired: