How to keep session alive in ASP.Net using Webservice and jQuery

Most of the time when we develop intranet web applications, our clients request us that they only have to log in in the morning when they reach office. It seems very easy to implement i.e. increase session timeout to 10+ hours and we are done.

But there is a drawback of this approach. Even if user close the browser, session's data will occupy server's memory till 10+ hours and our site's performance will go down. So, this is certainly not a good choice for us.

There are many alternates to solve above problem. In this post, I am sharing one of the possible solution.

First I have created an asmx service i.e. SessionAlive:-

/// <summary>
    /// Summary description for SessionAlive
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SessionAlive : System.Web.Services.WebService
    {
 
        [WebMethod]
        public void UpdateSession()
        {
            HttpContext.Current.Session["tempVariable"] = DateTime.Now;
        }
    }

Note that by default [System.Web.Script.Services.ScriptService] is commented when you create a new service. You need to uncomment above line to ensure that methods in this service are accessible for javascript or jQuery.

Also i have created UpdateSession() method which updates a value in session.

Now here is the javascript which I added in my page.

<script type="text/javascript" src="JS/jquery-1.4.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        setTimeout(updateSession, 1000*60);//Timeout is 1 min
    });
    
    function updateSession() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "SessionAlive.asmx/UpdateSession",
            data: "{}",
            dataType: "json"
        });
        setTimeout(updateSession, 1000 * 60);
    }
</script>

Above function calls web service after every minute to ensure that session is not time out. Hopefully this will be useful for you. Feel free to add comments and suggestions.