Prevent Redirect to Login Page when Session Times Out [ASP.NET]
- In the
global.asax file, add the following code to the Session_Start event handler:
protected void Session_Start()
{
int sessionTimeoutMinutes = 20; // Set the desired timeout value in minutes
Session.Timeout = sessionTimeoutMinutes;
Session["LastActivityTime"] = DateTime.Now;
}
- In your application's JavaScript file or
<script> tag, add the following code to handle user interactions and update the session's last activity time:
$(document).ready(function() {
$(document).on('mousemove keydown scroll', function() {
updateSessionLastActivityTime();
});
function updateSessionLastActivityTime() {
$.ajax({
url: '/Session/UpdateLastActivityTime',
type: 'POST',
success: function(response) {
// Handle the response if needed
}
});
}
startSessionTimeoutCountdown();
});
function startSessionTimeoutCountdown() {
var sessionTimeoutMinutes = @(Session.Timeout);
var sessionTimeoutMilliseconds = sessionTimeoutMinutes * 60 * 1000;
setTimeout(function() {
window.location.href = '/TimeoutPage';
}, sessionTimeoutMilliseconds);
}
- Create a server-side action to handle the AJAX request and update the session's last activity time:
[HttpPost]
public ActionResult UpdateLastActivityTime()
{
Session["LastActivityTime"] = DateTime.Now;
return Json(new { success = true });
}
You can handle session timeout without using an AJAX request by configuring it in the web.config file.
- Open the web.config file of your ASP.NET application.
- Locate the <system.web> section.
- Add or modify the following session-related settings:
<system.web>
<sessionState timeout="20" />
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="20" slidingExpiration="true" />
</authentication>
</system.web>
Hope it's Help !!