Home > Back-end >  asp.net C# keep the session alive as long as the user is active
asp.net C# keep the session alive as long as the user is active

Time:12-23

I made a simple web app using asp.net C# and I made a code to logout automatically from the website and redirect the user to the login page when the session expire, but I have a problem which is the website logout and redirect the user to the login page even if the user is active and clicking on buttons and moving the mouse and in this case I want the session to be alive and make it expire when the user don't do anything during the timeout period just like most of the websites.

Here is my code to end session:

web.config:

<sessionState timeout="1"></sessionState>

main_page.aspx:

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    AutoRedirect();
}

public void AutoRedirect()
{
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 6000);
    string str_Script = @"
           <script type='text/javascript'> 
               intervalset = window.setInterval('Redirect()',"  
                   int_MilliSecondsTimeOut.ToString()   @");
               function Redirect()
               {
                   window.location.href='/login.aspx'; 
               }
           </script>";

    ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", str_Script);
}

CodePudding user response:

let not talk about Application's timeout How to set session timeout in web.config

In your Javascript I think you need to stop setInterval Stop setInterval call in JavaScript

so why not use all task in aspx page 's javascript like

$(document).ready(function(){
     ResetTheTimer();
     $('body').mousemove(function() { // or other events
           ResetTheTimer();
           alert('clear!');
     });
 
});
var intervalset ;
var MilliSecondsTimeOut = 12000;
function ResetTheTimer(){
    
    clearInterval(intervalset);
    intervalset = window.setInterval(Redirect,  MilliSecondsTimeOut );
             
}
  function Redirect()
  {alert(1);   
  //window.location.href='/login.aspx'; 
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

And then to make application alive you need some interval to postback to code behind too.

  • Related