Alex Alex - 1 year ago 137
ASP.NET (C#) Question

Keeping ASP.NET Session Open / Alive

Which is the easiest and most unobstrusive way to keep an ASP.NET session alive as long as the user has the browser window open? Is it timed AJAX calls? I want to prevent the following: sometimes users keep their window open for a long time, then enter stuff, and on submit nothing works anymore because the server side session expired. I don't want to increase the timeout value for more than 10 min on the server as I want closed sessions (by closing the browser window) to time out fast.

Suggestions, code samples?

Answer Source

I use JQuery to perform a simple AJAX call to a dummy HTTP Handler that does nothing but keeping my Session alive:

function setHeartbeat() {
    setTimeout("heartbeat()", 300000); // every 5 min

function heartbeat() {
        function(data) {
            //$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)

Session handler can be as simple as:

public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState
    public bool IsReusable { get { return false; } }

    public void ProcessRequest(HttpContext context)
        context.Session["Heartbeat"] = DateTime.Now;

The key is to add IRequiresSessionState, otherwise Session won't be available (= null). The handler can of course also return a JSON serialized object if some data should be returned to the calling JavaScript.

Made available through web.config:

    <add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/>

added from balexandre on August 14th, 2012

I liked so much of this example, that I want to improve with the HTML/CSS and the beat part

change this

//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)


beatHeart(2); // just a little "red flash" in the corner :)

and add

// beat the heart 
// 'times' (int): nr of times to beat
function beatHeart(times) {
    var interval = setInterval(function () {
        $(".heartbeat").fadeIn(500, function () {
    }, 1000); // beat every second

    // after n times, let's clear the interval (adding 100ms of safe gap)
    setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100);


<div class="heartbeat">&hearts;</div>

.heartbeat {
    position: absolute;
    display: none;
    margin: 5px;
    color: red;
    right: 0;
    top: 0;

here is a live example for only the beating part: