Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Last active February 2, 2023 00:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save KyleMit/aa4f576fa32bf36fbedab5540c18211d to your computer and use it in GitHub Desktop.
Save KyleMit/aa4f576fa32bf36fbedab5540c18211d to your computer and use it in GitHub Desktop.
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
Copy link

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

@phamcongson
Copy link

Thanks you, code very good.
Change:
[SessionUpdater.Setup('@Url.Action("KeepSessionAlive","home")');]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment