Home >Backend Development >C++ >How Can AJAX Calls Keep ASP.NET Sessions Alive?

How Can AJAX Calls Keep ASP.NET Sessions Alive?

Linda Hamilton
Linda HamiltonOriginal
2025-01-13 07:56:46225browse

How Can AJAX Calls Keep ASP.NET Sessions Alive?

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

  • Discreet Operation: Session maintenance is transparent to the user.
  • Session Persistence: Sessions remain active as long as the browser window is open.
  • Flexible Frequency: The heartbeat interval is easily adjustable.
  • Improved User Experience: Ensures uninterrupted user sessions.

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!

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