Session does not sync with ASP.NET web application

I am developing an ASP.NET 3.5 WebForms application where I want a session to time out after a certain period of time. After which, if the user is trying to do something, the application should redirect them to a page that indicates that the session is completed and that they will need to start all over again. As far as I know, as far as I know.

However, I cannot get the session timeout to test this functionality, either from within Visual Studio or from IIS. Here are my session state settings in web.config:

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="<ConnectionString>" cookieless="false" timeout="1" /> 

This is how I test the 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 seems that Session.IsNewSession always returns false , which makes sense because the Session_End method is never called in my Global.asax.cs. What am I missing?

+4
source share
2 answers

Here is what I ended up implementing.

In Global.asax.cs:

 protected void Session_Start(object sender, EventArgs e) { Session[SessionKeys.SessionStart] = DateTime.Now; } 

In the base class of my pages:

 public bool IsSessionTimeout { get { DateTime? sessionStart = Session[SessionKeys.SessionStart] as DateTime?; bool isTimeout = false; if (!sessionStart.HasValue) { // If sessionStart doesn't have a value, the session has been cleared, // so assume a timeout has occurred. isTimeout = true; } else { // Otherwise, check the elapsed time. TimeSpan elapsed = DateTime.Now - sessionStart.Value; isTimeout = elapsed.TotalMinutes > Session.Timeout; } Session[SessionKeys.SessionStart] = DateTime.Now; return isTimeout; } } 
+1
source

I'm doing it:

  if (Session["myUser"] != null) myUser = (User)Session["myUser"]; else myUser = null; //User must be logged in, if not redirect to the login page - unless we are already running the login page. if ((myUser == null) && (Request.Url.AbsolutePath != "/Login.aspx")) Response.Redirect("Login.aspx?Mode=Timeout", true); 

on the homepage page of my one of my sites. You can easily adapt it to whatever you want. Basically, check for something that should exist in the session, and if it isn't there, your session will time out and you can take the appropriate action.

In my case, they are redirected to the login page. In your case, when they start their "process", you set a session variable. In each page request, see if this item is saved in the session.

+2
source

All Articles