ASP.NET Push Redirect on Session Timeout

前端 未结 10 1883
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:49

    Using Custom Page class and Javascript also we can achieve it.

    Create a custom pagebase class and write the common functionality codes into this class. Through this class, we can share the common functions to other web pages. In this class we need inherit the System.Web.UI.Page class. Place the below code into Pagebase class

    PageBase.cs

    namespace AutoRedirect
    {
        public class PageBase : System.Web.UI.Page
        {
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                AutoRedirect();
            }
    
            public void AutoRedirect()
            {
                int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000);
                string str_Script = @"
                   ";
    
               ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
            }
        }
    }
    

    Above AutoRedirect function will be used to redirect the login page when session expires, by using javascript window.setInterval, This window.setInterval executes a javascript function repeatedly with specific time delay. Here we are configuring the time delay as session timeout value. Once it’s reached the session expiration time then automatically executes the Redirect function and control transfer to login page.

    OriginalPage.aspx.cs

    namespace appStore
    {
        public partial class OriginalPage: Basepage
        {
            protected void Page_Load(object sender, EventArgs e)
            {
            }     
        }
    }
    

    OriginalPage.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="OriginalPage.aspx.cs" Inherits="AutoRedirect.OriginalPage" %>
    

    Web.config

        
        
    
    

    Note: The advantage of using Javascript is you could show custom message in alert box before location.href which will make perfect sense to user. In case if you don't want to use Javascript you could choose meta redirection also

    public void AutoRedirect()
    {
        this.Header.Controls.Add(new LiteralControl(
            String.Format("",
                this.Session.Timeout * 60, "login.aspx")));
    }
    

提交回复
热议问题