Click here to Skip to main content
15,891,607 members
Articles / Web Development / ASP.NET

How to Redirect to Another Page when Session Timeout in ASP.NET (when pages contain Ajax UpdatePanel)

Rate me:
Please Sign up or sign in to vote.
4.88/5 (25 votes)
18 Jun 2008CPOL 241.2K   63   41
A small solution to deal with session timeout when using Ajax UpdatePanel

Introduction

Session timeout in ASP.NET is such an important problem with web developer. When session ends, we run into some exceptional situations. There are also many solutions to deal with this problem on the Internet. But few of them have discussed about redirecting to another page when there is session timeout, especially when we work with Ajax UpdatePanel.

So, I suggest a way to do this.

Solution

My main idea is: 3 minutes before session is gone, we will alert the user to save his/her data or make any postbacks. If user still does not do anything, then 5 milliseconds before session goes, we will redirect the page to Login.aspx (or just refresh page by redirecting to itself).

Using the Code

Add the following code to your Master page:

C#
private void CheckSessionTimeout()
{
    string msgSession = 'Warning: Within next 3 minutes, if you do not do anything, '+
               ' our system will redirect to the login page. Please save changed data.';
    //time to remind, 3 minutes before session ends
    int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000; 
    //time to redirect, 5 milliseconds before session ends
    int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5; 

    string str_Script = @"
            var myTimeReminder, myTimeOut; 
            clearTimeout(myTimeReminder); 
            clearTimeout(myTimeOut); " +
            "var sessionTimeReminder = " + 
		int_MilliSecondsTimeReminder.ToString() + "; " +
            "var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
            "function doReminder(){ alert('" + msgSession + "'); }" +
            "function doRedirect(){ window.location.href='login.aspx'; }" + @"
            myTimeReminder=setTimeout('doReminder()', sessionTimeReminder); 
            myTimeOut=setTimeout('doRedirect()', sessionTimeout); ";

     ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), 
           "CheckSessionOut", str_Script, true);
}
C#
private void Page_Load(object sender, System.EventArgs e)
{
    this.CheckSessionTimeout();
}

If you do not want to redirect to login page, you can just refresh the page by replacing it by this code:

JavaScript
function doRedirect(){ window.location.href=window.location.href; }

If you do not use ScriptManager, you can replace with Page.RegisterClientScriptBlock(...)

Hope this helps.

History

  • 18th June, 2008: Initial post 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Vietnam Vietnam
MCSD, MSc
http://www.sirvina.com

Comments and Discussions

 
QuestionGreat solution, you are genius Nguyen Pin
Siamak.NET2-May-14 7:33
Siamak.NET2-May-14 7:33 
Questionsession Pin
aashish tyagi2-Apr-14 20:47
aashish tyagi2-Apr-14 20:47 
QuestionHelp Pin
charmax12-Dec-12 11:03
charmax12-Dec-12 11:03 
GeneralMy vote of 5 Pin
Chandrashekar SK7-Aug-12 4:41
Chandrashekar SK7-Aug-12 4:41 
QuestionYour code is simple and works nicely - I adapted to VB.NET and used on the site's Master Page Pin
jacklennon10-Feb-12 5:19
jacklennon10-Feb-12 5:19 
GeneralMy vote of 5 Pin
jacklennon10-Feb-12 5:10
jacklennon10-Feb-12 5:10 
QuestionExcellente article! Thanks Pin
Bruno Lemos27-Oct-11 6:23
Bruno Lemos27-Oct-11 6:23 
GeneralMy vote of 5 Pin
digjam94229-Mar-11 20:36
digjam94229-Mar-11 20:36 
Generallogin.aspx Pin
Ajay Kale New27-Sep-10 0:17
Ajay Kale New27-Sep-10 0:17 
Generalre automatic redirection to Login.aspx Pin
Ajay Kale New9-Sep-10 2:34
Ajay Kale New9-Sep-10 2:34 
Questionhow to create secured login page Pin
appusri53874-Nov-09 1:56
appusri53874-Nov-09 1:56 
QuestionHow to add session renew state to the alert box? Pin
Robert H.12-Aug-08 7:59
Robert H.12-Aug-08 7:59 
AnswerRe: How to add session renew state to the alert box? Pin
Nguyen Quy Minh12-Aug-08 20:28
Nguyen Quy Minh12-Aug-08 20:28 
GeneralRe: How to add session renew state to the alert box? Pin
Robert H.13-Aug-08 9:31
Robert H.13-Aug-08 9:31 
GeneralRe: How to add session renew state to the alert box? Pin
Nguyen Quy Minh13-Aug-08 19:07
Nguyen Quy Minh13-Aug-08 19:07 
GeneralRe: How to add session renew state to the alert box? Pin
Robert H.14-Aug-08 5:37
Robert H.14-Aug-08 5:37 
GeneralRe: How to add session renew state to the alert box? Pin
rcarroll14-Jan-09 10:20
rcarroll14-Jan-09 10:20 
GeneralRe: How to add session renew state to the alert box? Pin
ksalvage15-Jan-09 3:52
ksalvage15-Jan-09 3:52 
The alert box is a modal dialog in the browser so it could well be that the thread that the timer is running in is suspended while the alert is being displayed. I'm not sure how browsers treat timers running in the main context, or how the threading model works internally. A better solution would be to create a div that is hidden and show it when the time runs out.

I use the following code in my master page head:
<script language="javascript" type="text/javascript">
        function doRefresh(){ javascript:__doPostBack(''); }//window.location.href=window.location.href; }

        function doRedirect(){ window.location.href='login.aspx'; }
        
        function getStyleObject(objectId) {
            // checkW3C DOM, then MSIE 4, then NN 4.          
            if(document.getElementById && document.getElementById(objectId))             
	            return document.getElementById(objectId).style;            
            else if (document.all && document.all(objectId)) 
	            return document.all(objectId).style;            
            else if (document.layers && document.layers[objectId])  
	            return document.layers[objectId];            
            else             
	            return false;            
        }

        function setObjectVisibility(objectId, newVisibility) {            
            var styleObject = getStyleObject(objectId);                        
            if (styleObject) 
            {
	            styleObject.visibility = newVisibility;
	            return true;
            } 
            else             
	            return false;            
        }

        function showUserMessage()
        {
            setObjectVisibility("userMessage","visible");
        }
        
        function hideUserMessage()
        {
            setObjectVisibility("userMessage","hidden");
        }
</script>

with a div that looks like this
<div id="userMessage" style="position: absolute; background-color: white; z-index: 1; 
                        display: block; top: 5px; left: 20px; visibility:hidden; border: 1px solid black;">
                        <table width="400" style="width: 200px; height: auto; 
                            background-color:white;">
                            <tr>
                                <td>
                                    Warning: Within next 3 minutes, if you do not do anything, the system will redirect
                                    to the login page. Please save changed data.
                                </td>
                            </tr>
                            <tr>
                                <td align="right"><asp:Button CssClass="groupButton" ID="btnStillHere" OnClientClick="doRefresh()" Text="OK" runat="server" /></td>
                            </tr>
                        </table>                      
                    </div>

and this in my code behind:
protected void Page_Load(object sender, EventArgs e)
{
    CheckSessionTimeout();
}

private void CheckSessionTimeout()
{
    //time to remind, 3 minutes before session end
    int int_MilliSecondsTimeReminder = (Session.Timeout * 60000) - 3 * 60000;
    //time to redirect, 5 miliseconds before session end
    int int_MilliSecondsTimeOut = (Session.Timeout * 60000) - 5;

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("<script language="\"javascript\"" type="\"text/javascript\"">");
    sb.AppendLine("var myTimeReminder, myTimeOut;");
    sb.AppendLine("clearTimeout(myTimeReminder);");
    sb.AppendLine("clearTimeout(myTimeOut);");
    sb.AppendFormat("var sessionTimeReminder = {0};\n", int_MilliSecondsTimeReminder);
    sb.AppendFormat("var sessionTimeout = {0};\n", int_MilliSecondsTimeOut);
    sb.AppendLine("myTimeReminder=setTimeout('showUserMessage()', sessionTimeReminder);");
    sb.AppendLine("myTimeOut=setTimeout('doRedirect()', sessionTimeout);");
    sb.AppendLine("</script>");
    Page.RegisterClientScriptBlock("CheckSessionOut", sb.ToString());

}


This works well for me

Life is a game. Play to win

GeneralRe: How to add session renew state to the alert box? Pin
Nguyen Quy Minh16-Jan-09 17:54
Nguyen Quy Minh16-Jan-09 17:54 
GeneralRe: How to add session renew state to the alert box? Pin
Basil PP18-Apr-18 20:42
Basil PP18-Apr-18 20:42 
QuestionWorks fine but confirm box comes even when I am working on screen Pin
chaggu9-Jul-08 12:03
chaggu9-Jul-08 12:03 
AnswerRe: Works fine but confirm box comes even when I am working on screen Pin
Nguyen Quy Minh9-Jul-08 23:25
Nguyen Quy Minh9-Jul-08 23:25 
QuestionRe: Works fine but confirm box comes even when I am working on screen Pin
chaggu10-Jul-08 3:22
chaggu10-Jul-08 3:22 
AnswerRe: Works fine but confirm box comes even when I am working on screen Pin
Nguyen Quy Minh11-Jul-08 6:12
Nguyen Quy Minh11-Jul-08 6:12 
GeneralRe: Works fine but confirm box comes even when I am working on screen Pin
chaggu24-Jul-08 4:19
chaggu24-Jul-08 4:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.