Prolonging ASP.NET Sessions with AJAX
Maintaining active ASP.NET sessions is vital for a smooth user experience. A robust method utilizes AJAX calls to periodically refresh the session, preventing timeouts.
Implementing an AJAX Session Heartbeat
This approach employs a jQuery AJAX call, recurring (e.g., every 5 minutes), to a dedicated HTTP handler: "SessionHeartbeat.ashx." This handler's sole purpose is session maintenance. The C# code for this handler is:
<code class="language-csharp">public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { context.Session["Heartbeat"] = DateTime.Now; } }</code>
The corresponding client-side JavaScript function is:
<code class="language-javascript">function setHeartbeat() { setTimeout("heartbeat()", 5*60*1000); // Every 5 minutes } function heartbeat() { $.get( "/SessionHeartbeat.ashx", null, function(data) { setHeartbeat(); }, "json" ); }</code>
Enhancing the User Interface
For visual feedback (and continued session maintenance), we can add CSS and HTML:
<code class="language-javascript">function beatHeart(times) { var interval = setInterval(function () { $(".heartbeat").fadeIn(500, function () { $(".heartbeat").fadeOut(500); }); }, 1000); // Beat every second // Clear interval after 'times' iterations (with 100ms buffer) setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100); } /* HEARBEAT CSS */ .heartbeat { position: absolute; display: none; margin: 5px; color: red; right: 0; top: 0; }</code>
Advantages of AJAX Session Heartbeats
The above is the detailed content of How Can AJAX Calls Keep ASP.NET Sessions Alive?. For more information, please follow other related articles on the PHP Chinese website!