How to Extend Session in ASP.NET

If you are building a web app using “Forms” as a mode of authentication, there’s really not much to it when it comes to extending a session automatically.

What I am suggesting is that your web session will extend on its own so long as you have defined slidingExpiration attribute in your web.config file like so:

<authentication mode="Forms"> 
    <forms name=".ASPXAUTH" loginUrl="~/Login.aspx" timeout="20" slidingExpiration="true"></forms> 
</authentication>

Now, if you are using the authentication mode as “Windows“, there’s no support for the slidingExpiration attribute. For that, you can implement a solution in jQuery by simply creating a dummy HTML file and calling it anything you like. In the example below, I’ve named it AjaxDemo.html. See code below.

One thing to note here is that I am concatenating Date and Time when making an asynchronous call to AjaxDemo.html. This is done to ensure that a unique value is returned from the server. This step is crucial in extending the session timeout beyond its default threshold of 20 minutes.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    <title>Session Timeout</title>
    <script type="text/javascript">
        var sessionDelay = 5000; // 5 seconds

        $(function () {
            $("#btnExtendSession").click( function () {
                keepAlive();              
            });
        });

        function keepAlive() {
            var d = new Date();
            $.get('AjaxDemo.html?=' + d.getTime(), function () {
                timer = setTimeout(keepAlive, sessionDelay);
                clearTimeout(timer);
            });
        }

    </script>
</head>
<body>
    <button id="btnExtendSession">Extend Session</button>
</body>
</html>

When you click on the button “Extend Session” and open dev tools,ย  inside the Network tab, you would notice a unique value appended to AjaxDemo.html’s query string. See below:

Hope you found the post useful.

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in jQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.