Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Heartbeat to Keep Session Alive in ASP.NET MVC
[HttpPost]
public JsonResult KeepSessionAlive()
{
return new JsonResult {Data = "Success"};
}
<script type="text/javascript">
// initialize Session Updater on page
SessionUpdater.Setup('@Url.Action("KeepSessionAlive","Default")');
</script>
// http://stackoverflow.com/a/14195869/1366033
SessionUpdater = (function () {
var clientMovedSinceLastTimeout = false;
var keepSessionAliveUrl = null;
var timeout = 5 * 1000 * 60; // 5 minutes
function setupSessionUpdater(actionUrl) {
// store local value
keepSessionAliveUrl = actionUrl;
// setup handlers
listenForChanges();
// start timeout - it'll run after n minutes
checkToKeepSessionAlive();
}
function listenForChanges() {
$("body").one("mousemove keydown", function () {
clientMovedSinceLastTimeout = true;
});
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
setTimeout(function () { keepSessionAlive(); }, timeout);
}
function keepSessionAlive() {
// if we've had any movement since last run, ping the server
if (clientMovedSinceLastTimeout && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function (data) {
// reset movement flag
clientMovedSinceLastTimeout = false;
// start listening for changes again
listenForChanges();
// restart timeout to check again in n minutes
checkToKeepSessionAlive();
},
error: function (data) {
console.log("Error posting to " & keepSessionAliveUrl);
}
});
}
}
// export setup method
return {
Setup: setupSessionUpdater
};
})();
@sagartanti

This comment has been minimized.

Copy link

commented Apr 26, 2018

not working i have tried it but the KeepSessionAlive in HomeController never gets called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.