I’m developing an ASP.NET 3.5 WebForms application where I would like the session to timeout after a certain period of time. After which, if the user tries to do anything, the application should redirect them to a page stating that the session has timed out and that they will need to start over. Pretty standard stuff, as far as I know.
However, I can’t seem to make the session timeout to test this functionality, either running from Visual Studio or from IIS. Here’s my session state settings in web.config:
<sessionState mode="SQLServer"
allowCustomSqlDatabase="true"
sqlConnectionString="<ConnectionString>"
cookieless="false"
timeout="1" />
Here’s how I’m testing for session timeout:
public bool IsSessionTimeout
{
get
{
// If the session says its a new session, but a cookie exists, then the session has timed out.
if (Context.Session != null && Session.IsNewSession)
{
string cookie = Request.Headers["Cookie"];
return !string.IsNullOrEmpty(cookie) && cookie.IndexOf("ASP.NET_SessionId") >= 0;
}
else
{
return false;
}
}
}
It appears that Session.IsNewSession always returns false, which makes sense, because the Session_End method never gets called in my Global.asax.cs. What am I missing?
Here’s what I ended up implementing.
In Global.asax.cs:
In my pages’ base class: