Monday, June 20, 2011

How to avoid Session Timeouts in an Asp.Net Page?

Regardless of the session timeout that is set in the IIS or in the web.congif file, we can increase the time limit of the sessions in one particular or many Asp.Net pages. Place the below JavaScript code in your Asp.Net page that need more time than the Session Timeout time,

<script language="javascript" type="text/javascript">
function fnKeepSessionAlive()
{
var myurl = "Activate_Session.aspx";

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



window.setTimeout("fnKeepSessionAlive();", 60000);
}

fnKeepSessionAlive();
</script>

The above JavaScript function called "fnKeepSessionAlive()" uses the XMLHttpRequest to call another Asp.Net page as an asynchronous request. So the request to the page is internal and there won’t be any postback actions visible in the client browser. This JavaScript function is called recursively for every minute. You can adjust the time to 5, 10 or any number of minutes as per your requirement.

Notes:
1. The time to call the function fnKeepSessionAlive() should not exceed the Session Timeout time.
2. Make sure "Activate_Session.aspx" is physically present in your application folder. This must be an aspx page with or without codes.

No comments :

Post a Comment