In this example i'll show how to detect the session timeout which occurs when user is idle for the time specified as Session.
Timeout,using C# asp.NET and if it is than redirect the user to login page to login again, for this i've set time out value in web.config file to 1 minute
<system.web>
<compilation debug="true"/>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="1">
</sessionState>
</system.web>
I've created three pages in this example , one is login page , when session expires , i redirect to this page , one is navigation page where i'll check if session is valid or not , if it is valid than only user will see this page other wise he gets redirected to login page
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSessionStart"
runat="server"
OnClick="btnSessionStart_Click"
Text="Start Session" /><br />
<br />
<br />
<asp:Button ID="btnCheck"
runat="server"
OnClick="btnCheck_Click"
Text="Check Session ID" />
<br />
<asp:TextBox ID="txtSession"
runat="server"
Width="266px">
</asp:TextBox><br />
<br />
<asp:Button ID="btnGO"
runat="server"
OnClick="btnGO_Click"
Text="Go to Other Page" />
<br />
<br />
</div>
</form>
</body>
</html>
And the code behind for this page is like
protected void btnSessionStart_Click
(object sender, EventArgs e)
{
Guid Session_id = Guid.NewGuid();
Session["SessionID"]
= Session_id.ToString();
}
protected void btnCheck_Click
(object sender, EventArgs e)
{
if (Session["SessionID"] != null)
txtSession.Text =
Session["SessionID"].ToString();
else
txtSession.Text =
"Session has expired";
}
protected void btnGO_Click
(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx");
}
Now the page where we want to check the session has timed out or not, we need to check it in the Page_Init event of the page , is session is not null than only user will be able to go to the page other wise he will get redirected to login page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnHome"
runat="server" OnClick="btnHome_Click"
Text="Home" /></div>
</form>
</body>
</html>
And the Code behind for this page is
protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
protected void btnHome_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
private void CheckSession()
{
if (Session["SessionID"] == null)
{
Response.Redirect("Login.aspx");
}
}
If we need to check this in all the pages of application than we can create a BaseClass and write the above mentioned code of CheckSession and Page_Init part and drive all ur pages from this class by typing BaseClassName in place of System.Web.UI.Page and it will check all pages for session timeout every time page is loaded
Download the C# Source Code 
Related Posts:
1. Detect Browser refresh to avoid events getting fired again in ASP .NET
2. ASP.NET Submit form on Enter Key Default submit Button
3. Register custom controls dlls and user controls ascx in ASP.NET
![]() |
||
|
|
![]() |
|
Mixx it!
|
add to del.icio.us saved by 0 users |











14 comments:
Nice article.But hope u know about forms authentication,where asp.net will automatically redirect to login page,if login url is specified.There is no need for checking session like this in all pages.Thanks
Amit,
Forms Authentication just avoids this kind of checkin session inevery page. Also the Session State creating, removing is taken care automatically and you dont need to explicitly create. This technique is ASP Day technique.
Thanks,
Harish
http://geekswithblogs.net/ranganh
u can write your own httm module, that cheking if session expired, and if that happened you allow redirect to login page
Yeah I probably wouldnt do it like that!!! As mentioned, use what built in, rather than dodgy session checking. You are wasting server memory!
Forms authentication and Session are completely unrelated, and have very different purposes. Therefore, a method to detect a Session timeout is still very useful. I would do it in an HttpModule or in Global.asax though.
Wouldn't it be better to use a base page class and build this method on your base page class...
In My opinion best place to check for session timeout would be the Global.asax file in the AcquireRequestState event.That removes the dependency on checking for every page.
I have a related article but that uses the new Session.IsNewSession instead of checking a certain session object.
Good article. However, it would be nice if you could write an article on how to tell the user that the page is going to expire in 2minutes or so as a popup. This happens without a postback on an idle page. eg. HSBC online banking website.
Nishanth Nair,
I have tried this in master page.
#region Session alert handling
bool implementSessionAlert = false;
try
{
implementSessionAlert = Convert.ToBoolean(ConfigurationManager.AppSettings["ImplementSessionAlert"]);
}
catch
{ /*do nothing */ }
if (implementSessionAlert)
{
Session[SessionKeys.UserSession] = DateTime.Now;
object objSection = ConfigurationManager.GetSection("system.web/sessionState");
// Get the section related object.
System.Web.Configuration.SessionStateSection sessionStateSection =
(System.Web.Configuration.SessionStateSection)objSection;
bool addAlert = true;
int minutesBeforePrefernce = 4;
try
{
minutesBeforePrefernce = Convert.ToInt32(ConfigurationManager.AppSettings["MinutesBeforePrefernce"]);
if (minutesBeforePrefernce >= sessionStateSection.Timeout.Minutes)
{
// TODO: log
addAlert = false;
}
}
catch
{ /*do nothing */ }
if (addAlert)
{
DateTime sessionStartTime = Common.GetSafeDateTimeFromSession(SessionKeys.UserSession);
DateTime alertAfterTime = sessionStartTime.AddMinutes(sessionStateSection.Timeout.Minutes - minutesBeforePrefernce);
TimeSpan alertAfter = alertAfterTime.Subtract(sessionStartTime);
string openBrace = "{";
string closBrace = "}";
string newLine = "\\\\r\\\\n\\\\r\\\\n";
string tab = "\\\\r";
string jscript =
string.Format("var timeOutId; timeOutId = setTimeout(\" var confirmResult = confirm('Session will end at {2} in {0} minutes. {5}{6}OK - to go to the landing page and start a new Session. {5}{6}Cancel - to stay on the current page. Canceling and interaction after session ends might cause unexpected results.'); if(confirmResult) {3} self.location = '.'; {4} /*else {3} alert(new Date().toLocaleTimeString()); {4}*/\", {1});",
minutesBeforePrefernce, alertAfter.TotalMilliseconds, sessionStartTime.AddMinutes(sessionStateSection.Timeout.Minutes).ToLongTimeString(), openBrace, closBrace, newLine, tab);
Page.ClientScript.RegisterStartupScript(
typeof(string),
"SessionTimeOutAlert",
jscript,
true);
}
}
#endregion
basically only these lines two matter.
string jscript =
string.Format("var timeOutId; timeOutId = setTimeout(\" var confirmResult = confirm('Session will end at {2} in {0} minutes. {5}{6}OK - to go to the landing page and start a new Session. {5}{6}Cancel - to stay on the current page. Canceling and interaction after session ends might cause unexpected results.'); if(confirmResult) {3} self.location = '.'; {4} /*else {3} alert(new Date().toLocaleTimeString()); {4}*/\", {1});",
minutesBeforePrefernce, alertAfter.TotalMilliseconds, sessionStartTime.AddMinutes(sessionStateSection.Timeout.Minutes).ToLongTimeString(), openBrace, closBrace, newLine, tab);
Page.ClientScript.RegisterStartupScript(
typeof(string),
"SessionTimeOutAlert",
jscript,
true);
This post has been removed by a blog administrator.
This post has been removed by a blog administrator.
Post a Comment