Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

Alert Session Time out in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.93/5 (40 votes)
27 Jul 2011CPOL2 min read 275K   11.6K   122   42
This article looks at ways to warn users about the session timeout.

Introduction

One of the requirements in my project was to warn users about the session expiry. Though it looks like a simple requirement for the end users, it is not the case for developers and designers. We need to deal with lot of scenarios in the real time application. What is the best way to achieve the objective? Some of the challenges would be like:

  1. Session is a sliding expiry value. It gets extended every time there is a post back.
  2. There are multiple ways that you can handle this scenario and each of them has its own technical challenges.

Approaches

The following section will try to cover few of the approaches to handle session expiry.

1. Provide a Simple Alert

In this approach, the user will be provided with a simple warning message, based on a pre-defined time interval.

JavaScript
<script language="javascript" type="text/javascript">
       var sessionTimeoutWarning = 
	"<%= System.Configuration.ConfigurationSettings.AppSettings
	["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";

        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionWarning()', sTimeout);

        function SessionWarning() {
var message = "Your session will expire in another " + 
	(parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)) + 
	" mins! Please Save the data before the session expires";
alert(message);
        }
</script>
  • sessionTimeoutWarning: is a predefined value in the application configuration. Say 18 minutes.
  • sessionTimeout: holds the session timeout interval. Say 20 minutes. In case the user does not do any post back on the page for about 18 minutes, he will be warned about the session expiry.

2. Provide a Simple Alert and Then Redirect the User to Home Page or Login Page

JavaScript
<script language="javascript" type="text/javascript">
      var sessionTimeoutWarning =
  "<%= System.Configuration.ConfigurationSettings.AppSettings
  ["SessionWarning"].ToString()%>";
      var sessionTimeout = "<%= Session.Timeout %>";
      var timeOnPageLoad = new Date();

      //For warning
      setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);
      //To redirect to the welcome page
      setTimeout('RedirectToWelcomePage()',parseInt(sessionTimeout) * 60 * 1000);

      //Session Warning
      function SessionWarning() {
          //minutes left for expiry
          var minutesForExpiry =  (parseInt(sessionTimeout) -
              parseInt(sessionTimeoutWarning));
          var message = "Your session will expire in another " + minutesForExpiry +
          " mins! Please Save the data before the session expires";
          alert(message);
          var currentTime = new Date();
          //time for expiry
          var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes()
              + parseInt(sessionTimeout));

          //Current time is greater than the expiry time
          if(Date.parse(currentTime) > timeForExpiry)
          {
              alert("Session expired. You will be redirected to welcome page");
              window.location = "../Welcome.aspx";
          }
      }

      //Session timeout
      function RedirectToWelcomePage(){
          alert("Session expired. You will be redirected to welcome page");
          window.location = "../Welcome.aspx";
      }
</script>

In this approach, the user will be warned about the session timeout. If user does not save or do any post back, he would be redirected to the login or home page, once the session interval time expires.

3. Extend User Session

JavaScript
 <script language="javascript" type="text/javascript">
        var sessionTimeoutWarning = 
	"<%= System.Configuration.ConfigurationSettings.AppSettings
	["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";
        var timeOnPageLoad = new Date();
        var sessionWarningTimer = null;
        var redirectToWelcomePageTimer = null;
        //For warning
        var sessionWarningTimer = setTimeout('SessionWarning()', 
				parseInt(sessionTimeoutWarning) * 60 * 1000);
        //To redirect to the welcome page
        var redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()',
					parseInt(sessionTimeout) * 60 * 1000);

        //Session Warning
        function SessionWarning() {
            //minutes left for expiry
            var minutesForExpiry =  (parseInt(sessionTimeout) - 
					parseInt(sessionTimeoutWarning));
            var message = "Your session will expire in another " + 
		minutesForExpiry + " mins. Do you want to extend the session?";

            //Confirm the user if he wants to extend the session
            answer = confirm(message);

            //if yes, extend the session.
            if(answer)
            {
                var img = new Image(1, 1);
                img.src = 'KeepAlive.aspx?date=' + escape(new Date());

                //Clear the RedirectToWelcomePage method
                if (redirectToWelcomePageTimer != null) {
                    clearTimeout(redirectToWelcomePageTimer);
                }
   	       //reset the time on page load
                timeOnPageLoad =  new Date();
                sessionWarningTimer = setTimeout('SessionWarning()', 
				parseInt(sessionTimeoutWarning) * 60 * 1000);
                //To redirect to the welcome page
                redirectToWelcomePageTimer = setTimeout
		('RedirectToWelcomePage()',parseInt(sessionTimeout) * 60 * 1000);
            }

            //*************************
            //Even after clicking ok(extending session) or cancel button, 
	   //if the session time is over. Then exit the session.
            var currentTime = new Date();
            //time for expiry
            var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + 
				parseInt(sessionTimeout)); 

            //Current time is greater than the expiry time
            if(Date.parse(currentTime) > timeForExpiry)
            {
                alert("Session expired. You will be redirected to welcome page");
                window.location = "../Welcome.aspx";
            }
            //**************************
        }

        //Session timeout
        function RedirectToWelcomePage(){
            alert("Session expired. You will be redirected to welcome page");
            window.location = "../Welcome.aspx";
        }
</script>   

In this approach, the user will be warned about the session timeout and provides the ability to extend user session. If the user confirms to extend the session, it gets extended. If user confirms after the session expiry timeout limit, even then the user will be logged out. Following lines of code are used to extend the user session. Where 'KeepAlive.aspx is a dummy page in the website.

JavaScript
var img = new Image(1, 1); 
img.src = 'KeepAlive.aspx?date=' + escape(new Date()); 

Note: In all the above scenarios, I am assuming SetTimeout method and session related variables will be reset whenever there is a post back. This may not work 100%, when there could be partial rendering and the SetTimeout method and session related variables may not be reset. All files are in the Samples folder.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
9+ plus years of experience in IT industry. This includes experience in architecting, designing and developing solutions on Web and desktop application platforms

Comments and Discussions

 
QuestionDidnot get SessionWaring Values.!!! Pin
Member 1223794813-Feb-18 18:42
Member 1223794813-Feb-18 18:42 
QuestionVb.Net Pin
Member 135108029-Nov-17 4:24
Member 135108029-Nov-17 4:24 
PraiseGood Job Pin
galappaththic23-May-16 23:22
galappaththic23-May-16 23:22 
GeneralMy vote of 1 Pin
ilkerKaran16-Nov-15 3:18
ilkerKaran16-Nov-15 3:18 
GeneralRe: My vote of 1 Pin
thund3rstruck13-Mar-17 14:28
thund3rstruck13-Mar-17 14:28 
QuestionThanks Manjunath Pin
Raja.Lakshman16-Jun-15 16:32
Raja.Lakshman16-Jun-15 16:32 
QuestionFunciona de 10 gracias Campion :) .... 10 works through Campion :) Pin
Member 1000494222-Aug-14 4:58
Member 1000494222-Aug-14 4:58 
GeneralGreat Post !! Pin
Danish Islam24-Jun-14 21:21
Danish Islam24-Jun-14 21:21 
QuestionGreat contribution Pin
gefahr1-Feb-14 15:05
gefahr1-Feb-14 15:05 
AnswerRe: Great contribution Pin
Manjunath Shrikantiah2-Feb-14 22:57
Manjunath Shrikantiah2-Feb-14 22:57 
AnswerRe: Great contribution Pin
Scott Perry10-Mar-14 5:45
Scott Perry10-Mar-14 5:45 
QuestionExtending the session - How does it work? Pin
Ciaran Gallagher8-Dec-13 22:45
Ciaran Gallagher8-Dec-13 22:45 
QuestionInput Extend time from user Pin
Sunny Setia16-Jul-13 0:05
Sunny Setia16-Jul-13 0:05 
GeneralMy vote of 5 Pin
Sunny Setia15-Jul-13 23:58
Sunny Setia15-Jul-13 23:58 
QuestionSession Expire when no button is clicked Pin
nandhy0431-May-13 11:08
nandhy0431-May-13 11:08 
QuestionAdding Yes/No buttons Pin
Member 998163212-Apr-13 9:46
Member 998163212-Apr-13 9:46 
GeneralMy vote of 5 Pin
NoName_ark26-Mar-13 9:39
NoName_ark26-Mar-13 9:39 
GeneralMy vote of 5 Pin
Logismia22-Nov-12 20:36
Logismia22-Nov-12 20:36 
QuestionNeed help to understand few line of code and its meaning for session expiry Pin
Tridip Bhattacharjee15-Oct-12 8:34
professionalTridip Bhattacharjee15-Oct-12 8:34 
this below lines are not clear to me....can you please explain in details. thanks

C#
var currentTime = new Date();
            //time for expiry
            var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes()
                + parseInt(sessionTimeout));

            //Current time is greater than the expiry time
            if(Date.parse(currentTime) > timeForExpiry)
            {
                alert("Session expired. You will be redirected to welcome page");
                window.location = "../Welcome.aspx";
            }

tbhattacharjee

Questionregarding session management Pin
Tridip Bhattacharjee4-Oct-12 20:58
professionalTridip Bhattacharjee4-Oct-12 20:58 
QuestionFails if opens new tab Pin
Steve Montgomery7-Sep-12 1:01
Steve Montgomery7-Sep-12 1:01 
Generalimage(1,1) what is that.. please explain... Pin
pereubu12319-Jul-12 1:24
pereubu12319-Jul-12 1:24 
GeneralRe: image(1,1) what is that.. please explain... Pin
Manjunath Shrikantiah19-Jul-12 3:31
Manjunath Shrikantiah19-Jul-12 3:31 
GeneralRe: image(1,1) what is that.. please explain... Pin
pereubu12320-Jul-12 3:42
pereubu12320-Jul-12 3:42 
Questionreset the session Pin
wissam bishouty26-Apr-12 22:16
wissam bishouty26-Apr-12 22:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.