How To Achieve "Session Will Expire Soon" Notification

Notifying the users that the session is getting expired in a few minutes is good practice rather than logging them out directly. Let's see how to achieve this.

Notifying the users that the session is expiring in a few minutes is good practice rather than logging them out directly. Let's see how to achieve this. 
 
The "Session Timed Out" notification is very important because sometimes when a user is idle on the website,  generally we get them signed out directly once the timeout occurs and the user gets surprised. There are so many articles already written on session timeout. Therefore, in this blog, I will try to explain how to create a "Session Timeout" notification using jQuery. We can configure a session timeout and time duration for notification (the time needed to show the notification before the session expires) in a web.config file.
 
Let's start with some coding that will explain how we can implement a "Session Timeout" notification functionality in an ASP.NET MVC application through very simple steps.
 
Step 1
 
Create an MVC application.
 
Step 2
 
Set the Session timeout and duration for notification before the actual timeout in web.config as below. 
  1. </system.web>  
  2. <!--Put Value in Minutes only-->   
  3. <sessionState timeout="30"></sessionState>     
  4. </system.web>  
Here is the code of the notification time that we can configure in web.config file.
  1. <appSettings>    
  2.    <!--Put Value in Seconds only-->  
  3.    <add key="SessionExpNotice" value="60" />  
  4.    <add key="SessionExpireTime" value="1800" />   
  5.    <add key="AppPath" value="http://localhost:10334" />
  6. </appSettings>    
Step 3
 
Making a class with a private constructor to get a value of app settings is a good practice so I am doing the same here.  
  1. using System.Configuration;    
  2.     
  3. public class AppSetting    
  4. {    
  5. private  AppSetting()
  6. {}
  7. public static int SessionExpireTime    
  8.         {    
  9.             get { return Convert.ToInt32(ConfigurationManager.AppSettings["SessionExpireTime"]); }    
  10.         }    
  11. public static int SessionExpNotice    
  12.         {    
  13.             get { return Convert.ToInt32(ConfigurationManager.AppSettings["SessionExpNotice"]); }    
  14.         }    
  15. public static string AppPath  
  16.         {    
  17.             get { return Convert.ToString(ConfigurationManager.AppSettings["AppPath"]); }    
  18.         }    
  19. }    
Step 4
 
Now, create a common JavaScript file that will be linked to the layout(Master) page.
  1. var SessionTimer;    
  2. $(document).ready(function () {    
  3.     setInterval("fnSessionRun()", 1000);    
  4. });    
  5. function fnSessionRun() {    
  6.     SessionTimer -= 1;    
  7.     if (SessionTimer == 0) {    
  8.         window.location.href = $("#hdnAppPath").val() + '/Login';    
  9.     }    
  10.     if ($("#hdnSessionExpNotice").val() == SessionTimer) {    
  11.         $("#SessionExpNotice").modal('show');    
  12.     }    
  13. }    
  14.     
  15. function SessionOKClick() {    
  16.     //ajax call to reset session    
  17.     $.ajax({    
  18.         url: $("#hdnAppPath").val() + '/Common/ResetSession/',    
  19.         contentType: 'application/json',    
  20.         dataType: 'json',    
  21.         data: {},    
  22.         success: function (data) {    
  23.             $("#hdnSessionTimeout").val(parseInt(data));    
  24.             $("#SessionExpNotice").modal('hide');    
  25.         }    
  26.     });    
  27. }   
  28. $(document).ajaxStart(function (event, jqxhr, settings) {  
  29.     SessionTimer = parseInt($("#hdnSessionTimeout").val());  
  30. });  
Step 5
 
Now, create a layout page where we can create a div that will be opened with the notification. The layout has 2 hidden fileds that we used in the common JS file. These hidden fileds store the values of the Session Expiration time and the notification time that we mentioned in the web.config file. 
  1. <body>  
  2.  <input type="hidden" id="hdnAppPath" value="@AppSetting.AppPath" />  
  3.  <input type="hidden" id="hdnSessionTimeout" value="@AppSetting.SessionExpireTime" />  
  4.  <input type="hidden" id="hdnSessionExpNotice" value="@AppSetting.SessionExpNotice" />  
  5.   
  6. <div class="modal fadeIn" id="SessionExpNotice">  
  7.         <div class="modal-dialog modal-sm">  
  8.             <div class="modal-content">  
  9.                 <div class="modal-header">  
  10.                     <button id="btnConnectXeroClose" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>  
  11.                     <h4 class="modal-title" id="pnlTutorial">  
  12.                         <strong>  
  13.                             Session Expire Notice  
  14.                         </strong>  
  15.                     </h4>  
  16.                 </div>  
  17.                 <div class="modal-body">  
  18.                     Your session will expire in @AppSetting.SessionExpNotice seconds, Click Ok to remain logged in or click Cancel to log off.  
  19.                     If you are logged off any changes will be lost.  
  20.                 </div>  
  21.                 <div class="modal-footer">  
  22.                     <div class="sel">  
  23.                         <a onclick="return SessionOKClick()" href="#" class="btn btn-primary">  
  24.                             <i class="fa fa-save"></i>Ok  
  25.                         </a>  
  26.                         <a href="#" class="btn btn-primary" data-dismiss="modal">  
  27.                             <i class="fa fa-refresh"></i>Cancel  
  28.                         </a>  
  29.                     </div>  
  30.                 </div>  
  31.             </div>  
  32.         </div>  
  33.     </div>  
  34. </body>  
  35.   
  36. <script src="@Url.Content("~/Scripts/Common.js")"></script>  
Step 6
 
Now, create a common Controller that will handle the OK button. Click the AJAX Call and reset the session again.
  1. public class CommonController : Controller  
  2. {  
  3. #region Session Expire Notification  
  4.   
  5. public JsonResult ResetSession()  
  6. {  
  7.     return Json(Session.Timeout, JsonRequestBehavior.AllowGet);  
  8. }  
  9.  
  10. #endregion  
  11. }  
That's it. Using these simple steps, we can implement the session timeout notification.