Last active
February 2, 2023 00:26
-
-
Save KyleMit/aa4f576fa32bf36fbedab5540c18211d to your computer and use it in GitHub Desktop.
Heartbeat to Keep Session Alive in ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpPost] | |
public JsonResult KeepSessionAlive() | |
{ | |
return new JsonResult {Data = "Success"}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
// initialize Session Updater on page | |
SessionUpdater.Setup('@Url.Action("KeepSessionAlive","Default")'); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}; | |
})(); |
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
not working i have tried it but the KeepSessionAlive in HomeController never gets called.