Keeping ASP.NET Session Open/Alive

Keeping ASP.NET Session Open / Alive

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()", 5*60*1000); // every 5 min
}

function heartbeat() {
$.get(
"/SessionHeartbeat.ashx",
null,
function(data) {
//$("#heartbeat").show().fadeOut(1000); // just a little "red flash" in the corner :)
setHeartbeat();
},
"json"
);
}

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:

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

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 :)

into

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 () {
$(".heartbeat").fadeOut(500);
});
}, 1000); // beat every second

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

HTML and CSS

<div class="heartbeat">♥</div>

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

here is a live example for only the beating part: http://jsbin.com/ibagob/1/

asp.net C# keep the session alive as long as the user is active

let not talk about Application's timeout
How to set session timeout in web.config

In your Javascript I think you need to stop setInterval
Stop setInterval call in JavaScript

so why not use all task in aspx page 's javascript like

$(document).ready(function(){
ResetTheTimer();
$('body').mousemove(function() { // or other events
ResetTheTimer();
alert('clear!');
});

});
var intervalset ;
var MilliSecondsTimeOut = 12000;
function ResetTheTimer(){

clearInterval(intervalset);
intervalset = window.setInterval(Redirect, MilliSecondsTimeOut );

}
function Redirect()
{alert(1);
//window.location.href='/login.aspx';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

how to alive session as long as possible in asp.net 3.5

Here is a working example for the OP.

Web.config - Set small timeout for testing

<sessionState mode="InProc" timeout="2"/>

Javscript (in page for this example)

<script type="text/javascript">
var interval = null;
(function() {
// keep me alive
interval = setInterval(function (){
$.get('keepalive.ashx', function (d) {
$('#response').append(d + '<br/>');
});
}, 30000);
})();


// If we want to stop the interval....
function Stop() {
clearInterval(interval);
}
</script>

This prints the sessionId in an element called response so we can see the session id.

keepalive.ashx Generic handler (needs System.Web.SessionState)

public class keepalive : IHttpHandler, IRequiresSessionState {

public void ProcessRequest (HttpContext context) {
if (context.User.Identity.IsAuthenticated)
{
// authenticated sessions
context.Response.ContentType = "text/plain";
context.Response.Write("Auth:" + context.Session.SessionID);
}
else
{
// guest
context.Response.ContentType = "text/plain";
context.Response.Write("NoAuth:" + context.Session.SessionID);
}
}

Note: One thing that wasn't asked is is your keepalive supposed to be run on an authenticated session? If so, I wonder if there is also a cookie expiration issue?

How to prevent session keep alives

Once a request received to the server, the session will be updated and session will never be expired as you stated. You can make a workaround as below. Copy the code to Global.asax.

void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
DateTime? userLastActive = (DateTime?)HttpContext.Current.Session["UserLastActive"];
if (userLastActive.HasValue && DateTime.Now.Subtract(userLastActive.Value).Minutes > 15)
{
Session.Abandon();
return;
}

// Check if the request for background tasks
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
var action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
if (controller == "BackGroundTaskController" &&
action == "BackGroundTaskAction")
{
// ignore
return;
}

HttpContext.Current.Session["UserLastActive"] = DateTime.Now;
}
}

At each request the code below will be executed. You can set the variable "UserLastActive" to session object except for the periodical requests. You can then check for the last active time of the user and make the session end.

ASP.Net MVC keep session alive for as long as possible

There's a difference between Forms Authentication ticket validity and ASP.NET Session validity. Those are 2 completely unrelated things. What you have shown in your question is the forms authentication ticket validity which you have set to 180 minutes with sliding expiration.

How long would you advise to keep the session alive?

Both the ASP.NET Session (if you are using any) and the forms authentication ticket timeout should be set to the same value. Whether you keep the session alive for a long time or perform periodic pings to the server to keep the session alive would be exactly the same. So you'd better set the timeout to a sufficiently high value instead of hamerring your server with periodic requests.

This being said, if you are using ASP.NET Session, and you are storing this session InProc, you should know that the web server could decide to recycle your application at any time. For example this could happen if certain CPU/memory thresholds are hit. When this happens, if you are storing the session in memory, you will loose all information, no matter how long you have set the timeout value. You should consider using an out-of-process, distributed session storage in this case.



Related Topics



Leave a reply



Submit