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.
- </system.web>
- <!--Put Value in Minutes only-->
- <sessionState timeout="30"></sessionState>
- </system.web>
Here is the code of the notification time that we can configure in web.config file.
- <appSettings>
- <!--Put Value in Seconds only-->
- <add key="SessionExpNotice" value="60" />
- <add key="SessionExpireTime" value="1800" />
- <add key="AppPath" value="http://localhost:10334" />
- </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.
- using System.Configuration;
-
- public class AppSetting
- {
- private AppSetting()
- {}
- public static int SessionExpireTime
- {
- get { return Convert.ToInt32(ConfigurationManager.AppSettings["SessionExpireTime"]); }
- }
- public static int SessionExpNotice
- {
- get { return Convert.ToInt32(ConfigurationManager.AppSettings["SessionExpNotice"]); }
- }
- public static string AppPath
- {
- get { return Convert.ToString(ConfigurationManager.AppSettings["AppPath"]); }
- }
- }
Step 4
Now, create a common JavaScript file that will be linked to the layout(Master) page.
- var SessionTimer;
- $(document).ready(function () {
- setInterval("fnSessionRun()", 1000);
- });
- function fnSessionRun() {
- SessionTimer -= 1;
- if (SessionTimer == 0) {
- window.location.href = $("#hdnAppPath").val() + '/Login';
- }
- if ($("#hdnSessionExpNotice").val() == SessionTimer) {
- $("#SessionExpNotice").modal('show');
- }
- }
-
- function SessionOKClick() {
-
- $.ajax({
- url: $("#hdnAppPath").val() + '/Common/ResetSession/',
- contentType: 'application/json',
- dataType: 'json',
- data: {},
- success: function (data) {
- $("#hdnSessionTimeout").val(parseInt(data));
- $("#SessionExpNotice").modal('hide');
- }
- });
- }
- $(document).ajaxStart(function (event, jqxhr, settings) {
- SessionTimer = parseInt($("#hdnSessionTimeout").val());
- });
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.
- <body>
- <input type="hidden" id="hdnAppPath" value="@AppSetting.AppPath" />
- <input type="hidden" id="hdnSessionTimeout" value="@AppSetting.SessionExpireTime" />
- <input type="hidden" id="hdnSessionExpNotice" value="@AppSetting.SessionExpNotice" />
-
- <div class="modal fadeIn" id="SessionExpNotice">
- <div class="modal-dialog modal-sm">
- <div class="modal-content">
- <div class="modal-header">
- <button id="btnConnectXeroClose" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <h4 class="modal-title" id="pnlTutorial">
- <strong>
- Session Expire Notice
- </strong>
- </h4>
- </div>
- <div class="modal-body">
- Your session will expire in @AppSetting.SessionExpNotice seconds, Click Ok to remain logged in or click Cancel to log off.
- If you are logged off any changes will be lost.
- </div>
- <div class="modal-footer">
- <div class="sel">
- <a onclick="return SessionOKClick()" href="#" class="btn btn-primary">
- <i class="fa fa-save"></i>Ok
- </a>
- <a href="#" class="btn btn-primary" data-dismiss="modal">
- <i class="fa fa-refresh"></i>Cancel
- </a>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
-
- <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.
- public class CommonController : Controller
- {
- #region Session Expire Notification
-
- public JsonResult ResetSession()
- {
- return Json(Session.Timeout, JsonRequestBehavior.AllowGet);
- }
-
- #endregion
- }
That's it. Using these simple steps, we can implement the session timeout notification.