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

Posted in .Net,, C#, Client, Javascript, VB.Net
4 comments on “How to Prevent Avoid Session Timeout in an Asp.Net C# VB.Net Page
  1. Prakash Pradhan says:

    This is working fine. Awesome solution …

  2. Edgar Canelas says:

    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

    • code display says:

      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.

  3. Ronald Raymundo says:

    Thanks! it’s working fine on my application.

Leave a Reply

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