Home >Backend Development >C++ >How Can I Keep My ASP.NET Session Alive Using Unobtrusive AJAX?
Extended browser sessions often lead to server-side session timeouts. This article presents a non-intrusive method using timed AJAX requests to a dummy handler to address this issue, ensuring continuous session activity.
The following jQuery code initiates a recurring AJAX call to SessionHeartbeat.ashx
every five minutes. This simple ping refreshes the session's timeout counter.
<code class="language-javascript">function setHeartbeat() { setTimeout("heartbeat()", 5*60*1000); // 5-minute interval } function heartbeat() { $.get("/SessionHeartbeat.ashx", function(data) { // Session refresh confirmation setHeartbeat(); }, "json"); }</code>
SessionHeartbeat.ashx
This HTTP handler manages session lifespan. Implementing IRequiresSessionState
guarantees Session object access.
<code class="language-csharp">public class SessionHeartbeatHttpHandler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Session["Heartbeat"] = DateTime.Now; } }</code>
The handler is registered in web.config
:
<code class="language-xml"><httphandlers> <add path="SessionHeartbeat.ashx" type="SessionHeartbeatHttpHandler" validate="false" verb="GET,HEAD" /> </httphandlers></code>
A simple heartbeat animation provides visual confirmation of session maintenance. The following CSS and JavaScript create this effect.
<code class="language-javascript">function beatHeart(times) { var interval = setInterval(function () { $(".heartbeat").fadeIn(500).fadeOut(500); }, 1000); // 1-second beat setTimeout(function () { clearInterval(interval); }, (1000 * times) + 100); }</code>
<code class="language-css">.heartbeat { position: absolute; display: none; margin: 5px; color: red; right: 0; top: 0; }</code>
This solution effectively extends ASP.NET sessions for the duration of the browser window, maintaining form and application functionality.
The above is the detailed content of How Can I Keep My ASP.NET Session Alive Using Unobtrusive AJAX?. For more information, please follow other related articles on the PHP Chinese website!