Friday, September 9, 2011

How to redirect to the login page automatically when session timeout in C#

 On my last project my client ask me to do some thing so can after certain of time if the website page is in idle mode for a specified time(session timeout) then the current user should automatically redirect to the login page! very interesting. i took this a a challenge and thanks god i able to do this.

Here i am showing  how to redirect to the login page automatically when session timeout in C#

Write this code in to the masterpage's cs file

 protected override void OnPreRender(EventArgs e)
            this.HeadContent.Controls.Add(new LiteralControl(
                String.Format("<meta http-equiv='refresh' content='{0};url={1}'>",
                SessionTimeOutWithin * 60, PageToSentAfterSessionTimeOut)));
This will add a metatag into the page header which will refresh the CheckSessionTimeOut.aspx page after SessionTimeOutWithin* 60 seconds when the session timeout occurs.

//This the page to be refresh after sessioin timeout
public string PageToSentAfterSessionTimeOut
            get { return "CheckSessionTimeOut.aspx"; }

//This takes the Session.Timeout from the webconfig or from where the Session.Timeout is being set
 public int SessionTimeOutWithin
            get { return Session.Timeout; }

// Add this within the <system.web> tag in web.config file . Here i am set 1 min as Session timeout

    <sessionState mode="InProc" cookieless="true" timeout="1"></sessionState>

 This will set the session timeout as 1 minute

Mode: means what happens if page is in active mode , InProc means session timeout will increase 1 minute more after the page activity time but if the page is in idle for 1 minute then session timeout will occurs.

No comments:

Post a Comment