Home >Backend Development >C++ >How Can I Keep My ASP.NET Session Alive Using Unobtrusive AJAX?

How Can I Keep My ASP.NET Session Alive Using Unobtrusive AJAX?

Barbara Streisand
Barbara StreisandOriginal
2025-01-13 08:22:43927browse

How Can I Keep My ASP.NET Session Alive Using Unobtrusive AJAX?

Prolonging ASP.NET Sessions with Subtle AJAX Calls

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.

AJAX Implementation Details

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>

Session Handler: 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>

Web.config Configuration

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>

Enhancing User Experience with Visual Feedback

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn