How to Prevent Avoid Session Timeout in an Asp.Net C# VB.Net Page

As we knew that its a very big problem specially when developers provide a very large entry page to users. It will be Irritating for users after entering all data & then session timeout occur. To prevent or avoid session timeout problem, there is no fixed or specific or direct way to handle. But one can handle this problem using javascript asynchronous call. But one thing keep in mind that time to execute the javacript method must be less than your session timeout time. Otherwise the method will not work. So, carefully set the time against IIS or web.config file session time. The cross-browser javascript method is given below:

<script language="javascript" type="text/javascript">
    function Prevent_Session_Timeout() {
        var callerurl = "Prevent_Session.aspx";

        if (window.XMLHttpRequest) {
            xhttp = new XMLHttpRequest()
        else {
            xhttp = new ActiveXObject("Microsoft.XMLHTTP")
        }"POST", callerurl, true);

        window.setTimeout("Prevent_Session_Timeout();", 400);

    //Initial calling

Setting Up Session Timeout in Web.config:

     <sessionState timeout="500"></sessionState>

1. Just create an aspx page. Paste the above method under “asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”” line. The above Javascript method internally called without any reflection to user. Do this if you want this only for this page. [Code Available in below Download Link]

2. You must set the window. setTimeout time parameter which never exceed the session timeout time of your project.

3. Paste the code in your main master page in case of all pages. [Code Available in below Download Link]

4. The above cross browser Javascript method is same for both C# & VB.Net application.

Script Tested for the following browsers:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Download Code Example C#        Download Code Example VB.Net

4 thoughts on “How to Prevent Avoid Session Timeout in an Asp.Net C# VB.Net Page

  • November 16, 2014 at 9:40 am

    This is working fine. Awesome solution …

  • May 21, 2015 at 11:34 am

    in the 3ยบ line code -> ” var callerurl = “Prevent_Session.aspx”;” the file Prevent_Session.aspx doesn’t exist. it is supposoed to work without that file? tks

    • May 21, 2015 at 3:01 pm

      Nice, you have noticed. Unfortunately the file not added. No, If you don’t add this file the code won’t work since a server side invocation is required to keep your session alive. Just add a blank page with the said name. Let us know if anymore issue.

  • June 16, 2015 at 8:50 pm

    Thanks! it’s working fine on my application.


Leave a Reply

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

AlphaOmega Captcha Classica  –  Enter Security Code