PhillyNJ
PhillyNJ

Reputation: 3902

Check is aspx session expired via jquery ajax request

I use asp.net to manage the session state of my site. I also use jquery and $.ajax(...) for synchronous and asynchronous requests.

Normally, in asp.net if a users session times out, it can be detected via a full or partial post-back. However, suppose a partial or full-post-back does not occur because I am using jquery ajax calls to a static c# web method. Whats the best what to know if the session timeout?

Upvotes: 1

Views: 2095

Answers (3)

PhillyNJ
PhillyNJ

Reputation: 3902

The easiest solution was to force a post back at certain intervals.

<meta http-equiv="refresh" content="1800">

Upvotes: 0

Sudipta Kumar Maiti
Sudipta Kumar Maiti

Reputation: 1709

There are couple of approaches to achieve it.

Approach #1: Create a generic handler and implement the IReadOnlySessionStateinterface to access session variables from this handler. Use a ajax get request and access this generic handler which provides whether session is active or not.

Approach #2: Decorate a public method of your page with [WebMethod] (using System.Web.Services) and access this method through ajax get request which provides whether session is active or not.

But all these approaches should be used just to check session is active or expired. But if the session is active, it'll renew your session - it may not be desirable. Please check that option also.

Upvotes: 0

i would create a javascript interval to make a ajax request from time to time, something like this:

<script>
$(document).ready(function () {
    setInterval(function (){
        $.ajax({
            url: 'WebMethodhere',
            type: 'GET',
            success: function (result) {
                if(result!='true')
                {
                    //It means that the Session expired, so do somethig
                }
            }
        })
    },3000);
});
</script>

I used 3000ms in this example, but the time it's up to you.

And your webmethod could be really simple:

if(Session["WhateverSession"]==null)
{
    return false;
}
else
{
    return true;
}

Upvotes: 2

Related Questions