Detecting ASP.NET Session Timeouts
page 2 of 2
by Robert Boedigheimer
Feedback
Average Rating: 
Views (Total / Last 10 Days): 187753/ 94

Detecting Timeouts

The ASP.NET HttpSessionState class provides a useful IsNewSession( ) method that returns true if a new session was created for this request.  The key to detecting a session timeout is to also look for the ASP.NET_SessionId cookie in the request.  If this is a new session but the cookie is present, this indicates a timeout situation.  In order to implement this effectively for an entire web site, it is useful to utilize the “Base Page” concept described in a previous article.

basePageSessionExpire.cs

 public class basePageSessionExpire : System.Web.UI.Page
 {
    public basePageSessionExpire()
    {
    }


  override protected void OnInit(EventArgs e)
  {
       base.OnInit(e);


   //It appears from testing that the Request and Response both share the 
   // same cookie collection.  If I set a cookie myself in the Reponse, it is 
   // also immediately visible to the Request collection.  This just means that 
   // since the ASP.Net_SessionID is set in the Session HTTPModule (which 
   // has already run), thatwe can't use our own code to see if the cookie was 
   // actually sent by the agent with the request using the collection. Check if 
   // the given page supports session or not (this tested as reliable indicator 
   // if EnableSessionState is true), should not care about a page that does 
   // not need session
   if (Context.Session != null)
   {
    //Tested and the IsNewSession is more advanced then simply checking if 
   // a cookie is present, it does take into account a session timeout, because 
   // I tested a timeout and it did show as a new session
    if (Session.IsNewSession)
    {
     // If it says it is a new session, but an existing cookie exists, then it must 
   // have timed out (can't use the cookie collection because even on first 
   // request it already contains the cookie (request and response
     // seem to share the collection)
     string szCookieHeader = Request.Headers["Cookie"];
     if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     {
      Response.Redirect("sessionTimeout.htm");
     }  
    } 
   }
  }
}

sessionTimeout.htm

This can be any page on the site, example just redirects to this page so just show a simple "A timeout has occurred" message for this article.

Each other page on the site just needs to derive from this new base page instead of the default System.Web.UI.Page, so just change the line in the code behind class from ": System.Web.UI.Page" to ": basePageSessionExpire".  Each page should also set the EnableSessionState variable as appropriate:

  • false - page request does not access any session information (the base page uses this to know that it does not need to check for timeout on this request since it does not require session information) 
  • ReadOnly - page request uses session information but does not modify it
  • true - page request reads and updates session information

Conclusion

It is often useful to know for a given request whether the user’s session information is still present.  The technique demonstrated is a straightforward implementation that can be easily applied to an entire web site that uses cookie based ASP.NET Session objects. 

Send comments or questions to robertb@aspalliance.com.


View Entire Article

User Comments

Title: Background and How Sessions Are Implemented   
Name: Joseph
Date: 2012-04-17 1:54:09 AM
Comment:
partical example needed
Title: Showing practically the usage of sessions   
Name: praveen
Date: 2011-11-10 7:38:23 AM
Comment:
hello sir,

can u show me how to use sessions in our web applications like in aspx file. After reading ur this session article i understood the concept but unable to implement practically using ASP.Net with C#.

So plz help me . .

Thx,
praveen
prvngb@gmail.com
Title: Re: Feras   
Name: Robert Boedigheimer
Date: 2011-08-30 4:12:50 PM
Comment:
You're welcome, I unfortunately have not experienced this problem so I have not investigated or know of a work around.
Title: Re: Session is not expiring server side?   
Name: Feras
Date: 2011-08-30 3:44:34 PM
Comment:
Thanks Mr. Boedigheimer for your repley, kindly will you tell me if you have a work around to this issue? or if you know how to fix it?

Thanks a lot
Title: Re: Feras   
Name: Robert Boedigheimer
Date: 2011-08-30 3:16:28 PM
Comment:
The Forms Authentication feature is not directly related to the Session and the timeouts discussed here. It sounds like you have found a potential flaw with that feature, where you logout on the server and yet it still responds to the cookie as if they are still authenticated. The Session timeout is really a mechanism that allows the server to decide when it is safe to cleanup memory used by the session.
Title: Session is not expiring server side?   
Name: Feras
Date: 2011-08-30 12:31:13 PM
Comment:
Hello there,

Thanks for an amazing article. Probably my question is easy but it is driving me crazy... you see I have an applicaion and I am using ASP.net's membership but my issue is, if I login with user X and then I take X's cookie ".ASPXFORMSAUTH" info and then logout. I add the same cookie with the same info and enters the URL and the broswer just opens the page up...
Title: storing login/logout details in database.   
Name: mmg
Date: 2011-04-29 6:09:20 AM
Comment:
how i store login and logout details for the user into the database.i m working on asp.net c#
Title: Issue on a web farm   
Name: mrainsdon
Date: 2011-01-24 8:34:59 PM
Comment:
I had issues implementing this on our web farm. The issue with "ASP.NET_SessionId" Cookie already existing after the first redirect would cause an infinite redirect loop. Here is how I resolved it:
string szCookieHeader = Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
if (Session["DidIRedirectAtTimeout"] == null)
{
Session["DidIRedirectAtTimeout"] = "YES";
Response.Redirect("SessionTimedOut.aspx");
}
else
{
Session["DidIRedirectAtTimeout"] = null;
}
}

It seems to have fixed the issue.
Title: Thank you so much   
Name: Vivek Kumar
Date: 2011-01-09 11:48:47 PM
Comment:
Thanks for providing an article with information.
Title: Can I use with Master / Content pages   
Name: James
Date: 2010-11-05 10:59:12 PM
Comment:
I am using a master page with : System.Web.UI.MasterPage
Content pages with : System.Web.UI.Page

Your basePageSessionExpire.cs has
public class basePageSessionExpire : System.Web.UI.Page

Do I need your 'basePageSessionExpire.cs' for Content pages and another similar class for the Master page like:

'baseMasterPageSessionExpire.cs' with:
public class baseMasterPageSessionExpire : System.Web.UI.MasterPage
{
public baseMasterPageSessionExpire()
{
}

If not, can you tell me what is required?

Thanks
Title: Cant I put it in global.asax   
Name: Vipresh
Date: 2010-10-18 3:46:19 AM
Comment:
The beginrequest event doesnt have access to the session object My bad. So I guess if any any one wants they will hav to put it in Application_AcquireRequestState.
But I guess ur suggestion is more perfect cause if we put it in Application_AcquireRequestState then the code will fire for every request but instead we just need to put it in Session_Start and code will fire only once at the start of session and after wards onyl when the session has expired.

vipreshjha@hotmail.com
Title: Re: Vipresh   
Name: Robert Boedigheimer
Date: 2010-10-15 7:46:36 AM
Comment:
You can, I actually recommend you use the method below in comments 2/13/2008 where you place the updated code in global.asax Session_Start
Title: Cant I put it in global.asax   
Name: Vipresh
Date: 2010-10-15 5:09:26 AM
Comment:
Cant I put this code in beginrequest event of global.asax .
Title: Re: asp.net newbie   
Name: Robert Boedigheimer
Date: 2010-10-01 8:22:46 AM
Comment:
Actually on the first site visit, the Request.Header collection will contain all of the HTTP headers that were sent with the request (user agent, Accept-Encoding, etc). I use the Request.Header instead of using Request.Cookies because the ASP.NET_SessionId cookie that is created for the response to the first request, shows up in the Request.Cookies collection! I don't know why they chose to do that, to me the Request related collections should not contain Response related info, but that is what it does. That is why I don't use it, because otherwise it will always have a value even on the first request and my technique would not work.
Title: Http.header   
Name: asp,net newbie
Date: 2010-10-01 2:43:08 AM
Comment:
Thanks for taking the time to help me out and others.

As a newbie, I understand the Request.Headers and Request.Cookie collection as follows.
Are my assumptions correct?

On the first site visit, before loading the page, the browser has just sent a request(HTTP.REQUEST) to the webserver and therefore the Request.Header does not contain any info yet. But, like you had already pointed out, the Request.Cookies will always have the SESSION ID info.

After the webserver sends the response(HTTP.RESPONSE) to the browser, along with the cookie, thereafter the ASP.NET_SessionId info is present.

Hence, checking the Request.Header information instead of the Request.Cookies collection makes sense.

This is my understanding. Is this is correct?

Thanks.
Title: Thank You, very good article   
Name: asp.net newbie
Date: 2010-09-29 1:16:12 AM
Comment:
Thanks for providing an article with information well laid out and in an easy to understand manner.
Title: good   
Name: jimy
Date: 2010-07-21 2:26:03 AM
Comment:
its mindblowing
Title: thank you for your help   
Name: EnoTh
Date: 2010-07-03 10:54:07 AM
Comment:
This is the great article and working perfectly well.
Thank you for helping others.
Title: good   
Name: good
Date: 2010-06-09 1:58:49 AM
Comment:
good one........
Title: sql   
Name: Mallarapu.Sreekanth
Date: 2010-05-29 1:26:57 AM
Comment:
Sql is very useful for beginners..
Title: session object   
Name: Yamuna Mathew
Date: 2010-04-27 11:39:38 PM
Comment:
useful for beginers.....
Title: session object   
Name: ytamuna Mathew
Date: 2010-04-27 11:37:56 PM
Comment:
informative
Title: server transfer processing   
Name: Rahul Dongare,Nagpur
Date: 2010-04-08 1:38:09 AM
Comment:
ASP.NET provides a framework for storing data that is specific to an individual user with the Session object. In order to preserve server memory, ASP.NET implements a rolling timeout mechanism which discards the session information for a user if no request is seen within the timeout period (default 20 minutes which is reset with each request).
Title: session time out   
Name: kapil sharma
Date: 2010-03-30 4:14:49 AM
Comment:
this article is ok for new user
Title: comment   
Name: suresh
Date: 2010-03-22 4:44:34 AM
Comment:
not bad.Its ok...
Title: Well done   
Name: ram
Date: 2010-03-03 5:50:01 AM
Comment:
thanks, nice article.
Title: Re: Khemlal   
Name: Robert Boedigheimer
Date: 2010-02-26 7:13:59 AM
Comment:
Did you email me at robertb@aspalliance.com? Please resend as I have not received anything...
Title: no reply   
Name: khemlal chhetri
Date: 2010-02-26 5:17:50 AM
Comment:
hi i have sent u a review regarding my problem 1 week back and am still waiting for ur reply. Please respond me at the earliest.
hop i dont have to remind u again.
please.
Title: Server.transfer effect   
Name: Ashish
Date: 2010-02-21 11:34:28 PM
Comment:
ASP.NET provides a framework for storing data that is specific to an individual user with the Session object. A page can add information to the Session object, and any other page can then retrieve the information for the same user. In order to preserve server memory, ASP.NET implements a rolling timeout mechanism which discards the session information for a user if no request is seen within the timeout period (default 20 minutes which is reset with each request).
Title: Re: NIQ   
Name: Robert Boedigheimer
Date: 2010-02-17 5:54:31 PM
Comment:
Checking if a value is set in session does not work in general as it might have also just not been set (yet).
Title: Do not see how this helps (2)   
Name: NIQ
Date: 2010-02-14 2:02:24 PM
Comment:
.
1. Ok... have confirmed that Server.Transfer("...", false) does preserve the session vars
2. Still need answer on my first message, about the 'Detect Session Timeout'
Title: reTake   
Name: NIQ
Date: 2010-02-14 1:40:05 PM
Comment:
Please hold off on answering my concern as to Server.Transfer losing all session vars...
I am revising my code. A coding error may be the culprit.
...will post soon t.y.
Title: Server.transfer effect   
Name: NIQ
Date: 2010-02-14 1:11:22 PM
Comment:
.
I have also noticed that if using 'Server.Transfer' to redirect a page the session object is lost.
Does this implementation circumvent that scenario?

I see on the net that the way to keep the session intact is to use the overloaded version of redirect:
Response.Redirect("~/default.aspx", false);

why not use Server.Transfer("~/default.aspx", false); ?

Can anyone clear my fog? Thank you.
.
Title: correction   
Name: NIQ
Date: 2010-02-14 12:56:54 PM
Comment:
I meant the latter not the former. sorry
Title: Do not see how this helps   
Name: NIQ
Date: 2010-02-14 12:55:20 PM
Comment:
Is the timeout detection occuring in real time or upon access of a page?
If the former, then 'if sesssion(name) is nothing' is sufficient to detect a timeout?
Am I interpreting this correctly?
Title: session   
Name: Jayaveer
Date: 2010-01-29 12:08:22 AM
Comment:
Create Session:-
Session["name"]="jayaveer";
Retrieve Session:-
string txt=session["name"].Tostring();
Set time to Session:-
Session.TimeOut=5;(in mins)
Title: Re. Troner   
Name: Robert Boedigheimer
Date: 2009-12-23 7:51:11 AM
Comment:
The problem with using Application_OnEnd or Session_End from global.asax for this is that they are not fired with a user request. Normally web pages are requested and the ASP.NET code runs to generate a response, in this case these events are fired not due to a user request but because something has happened on the server (AppDomain ending or session timeout respectively). There is no reponse on which the cookies could be set. I would like to know why you feel it is necessary to write them out so I could suggest some other alternatives. Please email me at robertb@aspalliance.com if you want to discuss in more detail.
Title: Persist Session Variables Using Cookies   
Name: Troner
Date: 2009-12-22 4:40:27 PM
Comment:
Can cookies be accessible in APPLICATION_START of Global.asax? I'm thinking of writing my session variables into cookies when APPLICATION_END triggers and retrieving them from the cookies when application re-starts. Any thoughts on this? Thanks!
Title: Refer another page in asp.net   
Name: murugesan
Date: 2009-11-30 3:07:30 AM
Comment:
i have 2 pages like defaul1.aspx and default2.aspx,
i placed textbox control in defaul2.aspx but values should pass from defaul1.aspx for textbox(defaul2.aspx)
Title: Re: Subha   
Name: Robert Boedigheimer
Date: 2009-10-30 8:29:38 AM
Comment:
I tested it with both Firefox 3 and Firefox 2 and it worked fine. I used the version of code that is just in the global.asax inside Session_Start. Email me at robertb@aspalliance.com if you have more questions.
Title: asp.net   
Name: subha
Date: 2009-10-29 1:55:37 AM
Comment:
session.isnewsession is not working in mozilla firebox but it is working in IE ,can u give idea
Title: Re: Above article   
Name: Ramu
Date: 2009-10-26 3:10:08 AM
Comment:
This article explains about session in a very simple and easily understandable way
Title: Mr.   
Name: Anil Kumar Verma
Date: 2009-08-21 12:28:54 AM
Comment:
This article is very good for all those who need to know about the session & how to control the session timeout problem
Title: Re: AG Bian   
Name: Robert Boedigheimer
Date: 2009-08-20 1:27:56 PM
Comment:
I setup a quick test on my machine with VS 2008 and .NET 3.5. I created a "Session_Start" in global.asax and just have a check of Session.IsNewSession. When I start a fresh browser, go to the site, the Session.IsNewSession for me is true. Given that scenario, the check for the session cookie is required because each first request to the site from a user in a newly opened browser will have a Session.IsNewSession of true. Is it possible that you were testing without closing all of your browsers and opening a new one? You can also email me at robertb@aspalliance.com if you want to talk more directly.
Title: Cookieless   
Name: AG Bian
Date: 2009-08-20 10:52:45 AM
Comment:
Thank you for replying.
There is an observation that I would like to run through you. I am using Visual Studio 2008 and my .NET framework version is 3.5. When I ran my app in the debug mode, I noticed that when I first launched my app, "Session.IsNewSession" was "false". Before the session expired, this value was alway false no matter how many times I ran it. Only when the session expired and I tried to do something with the page that I landed on, this value was set to "true". So it seems that the condition "if (Session.IsNewSession)" alone is sufficient to test for session expiration. Am I missing anything?
Title: Re: AG Brian   
Name: Robert Boedigheimer
Date: 2009-08-19 4:37:59 PM
Comment:
I have not tried it with a cookieless implementation. Since the provided code is specifically looking for a cookie header you would need to modify it to look for the session id in the URL, but the IsNewSession would presumably work the same. I think the cookieless would be more problematic with "false" timeouts because anyone who created a favorite that had the session id embedded would likely always see a timeout when they use that link.
Title: Cookieless   
Name: AG Bian
Date: 2009-08-19 4:12:33 PM
Comment:
Does this technique work only if we are using cookie based session mangement? Is there is a way for cookieless session mangement?
Title: Re: GJ   
Name: Robert Boedigheimer
Date: 2009-08-05 8:57:59 AM
Comment:
The trick with that will be changing how the session cookies are issued so that the cookies for the other sites are not also transmitted to your subsite. Please email me at robertb@aspalliance.com so can discuss your configuration and get the right code.
Title: Issue when we have Subsite   
Name: GJ
Date: 2009-08-04 1:29:16 PM
Comment:
i have a issue implementing this. My application is a part(Subsite in IIS terminology) of a portal application or my application could be open only from one of the links in portal. That being said Session is managed by parent site or the portal.in the first instance instance when my application is open the session cokkie is present i get the session timeout message. how can i handle that???
Title: Greatest article to date!   
Name: Robert Aronovici
Date: 2009-06-30 11:47:15 PM
Comment:
I use this method to update the user table and determine when the "log off" in theory, which works like a champ!
Title: kamel   
Name: gazzah
Date: 2009-06-29 6:55:52 AM
Comment:
this is a usefull article
Title: Blocked Cookies   
Name: Andrew Baird
Date: 2009-06-12 10:11:19 PM
Comment:
The most useful thing I took out of this article was that you can use this test (Request.Headers["Cookie"] == null) to see if Cookies are not allowed by the client browser. Thanks!
Title: session expire   
Name: anoop
Date: 2009-04-29 11:50:27 AM
Comment:
hi , i need some more explanation because it doesn't work
Title: NET_SessionId stays unless the browser is closed   
Name: codera
Date: 2009-04-28 4:30:27 PM
Comment:
Thanks this was very helpful. I found that ASP.NET_SessionId doesn't go away until you close the browser. If you try to login with the same browser after redirecting to the timeout page, you go back to the timeout page because the .net_sessionid is still available in the cookie. Thanks
Title: Help   
Name: Fahad
Date: 2009-03-25 3:29:56 PM
Comment:
Pls it very urgent...
Title: Help   
Name: Fahad
Date: 2009-03-25 3:27:15 PM
Comment:
And also wer to write the codes.. in all pages of the web..
if dat s the case then vil b solution to check globally i.e. throughout the application!!!
Title: Help   
Name: Fahad
Date: 2009-03-25 3:25:19 PM
Comment:
Hi,
This is good article, but m using ASP.NET 2.0 n using VB.NET, can u help me to show how to use session state in stateserver Mode.
Pls help me....
Title: Thanks   
Name: Deepak
Date: 2009-03-24 8:16:10 AM
Comment:
Thanks for this tutorial, it really helps me. Thank you so much.
Keep writing such wonderful articles
Title: What the hell is this   
Name: Rahul
Date: 2009-03-24 8:14:36 AM
Comment:
It is often useful to know for a given request whether the user’s session information is still present. The technique demonstrated is a straightforward implementation that can be easily applied to an entire web site that uses cookie based ASP.NET Session objects.


What do you think , this is worst tutorial !
Title: Re: Morteza   
Name: Robert Boedigheimer
Date: 2009-03-11 8:26:18 AM
Comment:
If your web site does not normally issue cookies, it would not be strange that your first request would not see any cookies. After your first request is made to an ASP.NET page that uses session it will send the session id cookie to the browser. The browser itself is not aware of your server side session timeout, so there would be no good explanation for why no cookie would be present on a time out. The browser will continue to submit the in memory session cookie to your web site until you close the browser. Please email me at robertb@aspalliance.com if you want to discuss in more detail.
Title: Help me   
Name: morteza
Date: 2009-03-08 9:01:29 AM
Comment:
hi
when my program wants to run this line
Request.Headers("Cookie")
it return null for two situation
firstly,when page start
secondly,when page time out
Title: Re: Krupa Patel   
Name: Robert Boedigheimer
Date: 2009-02-11 7:43:01 AM
Comment:
It depends on what type of authentication you are using. Session.Abandon( ) will clear out the session variables for the given user, but if you are using Forms Authentication it does nothing to impact the token/cookie that was issued to indicate the user is logged in. You will want to use this in that case:

FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();

If you have additional questions, please email me at robertb@aspalliance.com so we can discuss.
Title: Session End   
Name: Krupa Patel
Date: 2009-02-11 3:15:36 AM
Comment:
Hi..
I am trying to end the session when i click on logout. but when i redirect to another page at that time that page is shown to me although i have logged out. i have used ,
session.Clear();
session.Abandon();
to end the session.
can anyone help me in this?
Title: Re: Ravikumar   
Name: Robert Boedigheimer
Date: 2009-01-30 8:03:19 AM
Comment:
Please email me at robertb@aspalliance.com so I can gather more details...
Title: Seesion Clear   
Name: Ravikumar
Date: 2009-01-27 1:48:13 AM
Comment:
Hi,
In my Application path i create a new folder. I read the data from this folder. After the read the data the session is expired. I no need to session is expired.Kindly give me one solution
Title: Re: Troner   
Name: Robert Boedigheimer
Date: 2009-01-22 10:27:31 AM
Comment:
The "base" is a keyword in C# to invoke methods defined in a "parent" up the inheritance chain. In this instance, the class is System.Web.UI.Page.
Title: Where is base declared?   
Name: Troner
Date: 2009-01-22 9:44:19 AM
Comment:
Hi Robert,

Great article! I just have one question though. In the line that says:

base.OnInit(e);

Where is base declared?

Thanks in advance.
Troner
Title: Re: Dracked   
Name: Robert Boedigheimer
Date: 2008-12-22 8:53:16 AM
Comment:
From your description below, it is behaving like I would expect... Please email me at robertb@aspalliance.com and we can discuss in more detail
Title: Page Back   
Name: Dracked
Date: 2008-12-17 6:46:14 AM
Comment:
Hi Robert,
sorry to resurrect this thread again, but I have a question.

I created the basePageSessionExpire class as follows:
public class basePageSessionExpire : System.Web.UI.Page
{
public basePageSessionExpire()
{
}

override protected void OnInit(EventArgs e)
{
base.OnInit(e);

Response.Cache.SetCacheability(HttpCacheability.NoCache);

if (Context.Session != null)
{
if (Session.IsNewSession)
{
string strCookieHeader = Request.Headers["Cookie"];

if ((null != strCookieHeader) && (strCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
// If there's an authenticated user, log them out
//
if (Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}

Session.Abandon();

Response.Redirect("login.aspx");
}
}
}
}
}

The Response.Cache.SetCacheability(HttpCacheability.NoCache) and
Session.Abandon() lines were added when trying to get past the problem
below...

I have an aspx page which was originally defined as:
public partial class Resources : System.Web.UI.Page
and which I changed to:
public partial class Resources : basePageSessionExpire

This page is called from the Main.aspx page which does not inherit from
the basePageSessionExpire class. When I leave the system idle for just
over a minute (the timeout that is set in web.config for test purposes
for the sessionstate) and click on the link to the Resources page, I get
taken to the login page as expected.

However, if I then hit the back button and get back to the Main page,
then click on the link to the Resources page again, I do not get
redirected to the login page, I get to the Resources page, but the
Session variables are not set -
Title: awesome   
Name: Manish
Date: 2008-12-12 7:31:19 AM
Comment:
This solves the mystry of sessions
Title: nice article   
Name: ramulu
Date: 2008-11-26 4:10:56 AM
Comment:
It was very nice article. We Handled in Our Project.
Title: Re: R.Brahma chary   
Name: Robert Boedigheimer
Date: 2008-09-30 8:00:53 AM
Comment:
I am not sure which expiration you are referring to. You can set expirations in IIS which specify to the browser how long they should consider the information in the cache to be "fresh" so it does not need to do a "is modified since" on the next request for that item. If you mean the session timeout, it is not really a per page setting. You can adjust the timeout using Session.Timeout = 5; which would set at timeout of 5 minutes. This would not just affect the given page, but all of the information in session will be "dropped" after 5 minutes.
Title: session   
Name: harini
Date: 2008-09-29 2:20:59 PM
Comment:
ok ,but little bit confusion when reading ur article
Bcoz u often mention same point,so we r confused,anyway it is so useful for me for learning abt Session
Thanks and continue to do like
Title: Session.IsNewSession always returns true after session time out   
Name: Rashmi
Date: 2008-09-29 4:37:10 AM
Comment:
Hello Robert,

I have created one base page and handed the session timeout check in that in the same way you provided in the example.

Things working fine sometimes but sometimes it is not working properly. After debugging we get to know that the property

Session.IsNewSession always returns true whenever session gets timeout. And the process goes in infinite loop as the

Session.IsNewSession never holds false value.

It seems I have similar problem faced by Mark Relly. But in my case there is no Virtual Directory.

I also tried by adding the code (Suggested in the FAQ with Mark) in the Session_Start for changing the cookie path. The

solution works for me but after deployment on our client's machine, the code creates problem. Session state is not

maintained there after adding the code.

Please provide any help.
Thanks in advance.
-Rashmi
Title: How maintain different expiration times for different web pages in asp.net2.0   
Name: R.Brahma chary
Date: 2008-09-27 9:23:12 AM
Comment:
hi,
How to maintain different expiration times for different web pages in asp.net2.0
Title: Re: Jeremy   
Name: Robert Boedigheimer
Date: 2008-09-22 8:42:38 AM
Comment:
What you have should work fine. You only need to set the cookie path if you use virtual directories, if so place it in Session_Start as you show.
Title: Active two sessions at a time   
Name: krishna
Date: 2008-09-22 2:48:21 AM
Comment:
Sir,
I want to know that how to active two sessions at a time.
That means keeping one session ative and open onther session.
sir please reply me by mail krishna.v419@gmail.com
Title: Base Page and Session_Start   
Name: Jeremy
Date: 2008-09-19 1:57:27 PM
Comment:
Hi great article.

I have placed the below code into Global.asax
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim oCookie As HttpCookie = Response.Cookies("ASP.NET_SessionID")
If Not (oCookie Is Nothing) Then
oCookie.Path = Request.ApplicationPath
End If
End Sub

And in my BasPage class I have placed this code
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
' Check for expired session
If Not (Context.Session Is Nothing) Then
' If this is a new session
If Session.IsNewSession Then
If Not IsNothing(Request.Headers("Cookie")) AndAlso Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
Response.Write("New session")
'Send to default page
Response.Redirect(ApplicationManager.AppPath)
End If
End If
End If
End Sub

Is this correct, or should the Global code for the setting of the path be in BasePage,obviously I am assuming no.

Thanks!
Title: much nice article   
Name: hash
Date: 2008-09-13 1:07:11 PM
Comment:
sir i want to kno that i want to fetch from database month and year from date colum by using session variable.
for this on the form1 i take 2 dropdown list boxes one contains month text and otherone contains year value.
and these values i want to use dynamically on the form2 load event. actually sir tell me the oracle or sql query syntax that the values that access by form 1 and used dynamically on form2. than you sir please solve my problem.
Title: Background and How Sessions Are Implemented   
Name: JAYAPRAKASH
Date: 2008-08-23 6:50:00 AM
Comment:
It was very nice article. We Handled in Our Project.
Title: SIR I WANA TO KNOW ABOUT WINDOW BACK BUTTON HOW IT IS WORKS FOR A SITE IN ASP.NET   
Name: SIR I WANA TO KNOW ABOUT WINDOW BACK BUTTON HOW IT IS WORKS FOR A SITE IN ASP.NET
Date: 2008-07-31 8:59:07 AM
Comment:
SIR I WANA TO KNOW ABOUT WINDOW BACK BUTTON HOW IT IS WORKS FOR A SITE IN ASP.NET
Title: KNOWEDGE   
Name: DEVESH
Date: 2008-07-15 4:26:40 AM
Comment:
SIR I WANA TO KNOW ABOUT WINDOW BACK BUTTON HOW IT IS WORKS FOR A SITE IN ASP.NET
Title: Thanx   
Name: Bino
Date: 2008-07-11 2:10:38 AM
Comment:
thanx

www.codepal.co.in
Title: Re: Maha   
Name: Robert Boedigheimer
Date: 2008-07-10 10:18:15 AM
Comment:
We will need to talk through your scenario in more detail to determine what is happening. Please email me at robertb@aspalliance.com so we can investigate
Title: Session timeout on opening new browser from the code   
Name: Maha
Date: 2008-07-09 10:29:36 AM
Comment:
I have two masterpages.
In first master page i have the code whick displays a list..If we click on one of the list item , It opens a new browser window using window.open.
The new opened window has another master page.
I am getting timeouts on this newly opened page intermittently and it is not consistent.
Sometimes on first navigation i am getting timeout , sometimes after 5 - 6 navigation it times out.
Everything works fine in my local machine.
But when deployed in Integration I am getting this issue.
Title: Can i use this code in the master page   
Name: Maha
Date: 2008-07-09 10:25:43 AM
Comment:
Can i use basePageSessionExpire in Master page
Title: ASP.NET   
Name: Ragunathan.M., MCA
Date: 2008-07-09 7:18:47 AM
Comment:
Good..
Title: log out code   
Name: prajeesh
Date: 2008-07-04 2:28:19 AM
Comment:
sir am facing a proublum in sign out
how sin out will work by using session
Title: comments   
Name: sun
Date: 2008-05-15 7:46:28 AM
Comment:
Fine
Title: asp.net   
Name: vasu
Date: 2008-05-07 1:41:00 AM
Comment:
i cont understand u r coding plz give properly information
Title: R.Sathish Kumar.,MCA   
Name: AnnaNagar-Chennai
Date: 2008-04-29 2:44:09 AM
Comment:
Good..
Title: Re: S.MaheshKumar   
Name: Robert Boedigheimer
Date: 2008-04-21 7:56:53 AM
Comment:
Please email me at robertb@aspalliance.com. In general, you can just create your hyperlink with more than one querystring value such as http://test.com?a=1&b=2&c=3. Then in your page code you can read with Request.QueryString["a"] and cast or convert it to the appropriate data type.
Title: Multiple values passing the QueryString   
Name: S.MaheshKumar
Date: 2008-04-19 8:06:40 AM
Comment:
Good Evening Robert,

The Problem With How Passing the Multiple Values to QueryString By using C#

thank you

Mahesh (India)
Title: Re: Mark Relly   
Name: Robert Boedigheimer
Date: 2008-04-16 11:36:38 AM
Comment:
Can you email me at robertb@aspalliance.com so we can investigate? Did you do any kind of trace to ensure that the request that was sent up actually had the original session id cookie? I would start with that to ensure that it is properly being sent with the path, etc.
Title: Re: Robert   
Name: Mark Relly
Date: 2008-04-16 4:17:19 AM
Comment:
Thanks Robert yes that makes sense but unfortunately doesn't work for me.

I understand that the cookies default path is "/" and was using the code to set this to the virtual directory name.

This seemed to work fine except that once a user logged in they were automaticaly directed back to the logon page.

This was caused because the session seems to lose what is added to the session (in my case the user details) after it directs away from the login page. It's almost like changing the path in the cookie (which I think actually creates a new cookie) causes a new session to be created and when a new session is created it sets the cookie path again so you get into a loop.

Basically when I added the code to set the path in cookie and then login to my application authentication passes I get redirected to the default page but once the default page starts executing it hits session_start again.

I think this is because I've changed the cookie but if this was the case I'd have expected others to have similar problems.

I hope I managed to explain ok. Thanks for the help
Title: Re: Mark relly   
Name: Robert Boedigheimer
Date: 2008-04-09 8:58:32 AM
Comment:
The problem with the default ASP.NET session cookie is that it sends out with a path of "/", so if you use virtual directories for different web sites on a server the same cookie is transmitted to both of the sites even though they do not share sesions. That trips up the detection code because the same condition appears (a new session is created but a cookie is present). To avoid that with virtual directories, you added the code properly. What that will do is setup the path so the cookie is only sent when your URL matches that path. So if your virtual directory name as "site1" then instead of a path of "/" the cookie will have a path of "/site1". The issue is that you need to exactly match the URL and the path of the cookie (including case sensitivity) for this to work. In my example below I used the ".ToLower( )" so that all of my links could consistently be all lower case. Check how your URLs are setup to your virtual directory, and take off ".ToLower( )" if it is not appropriate. Does that make sense?
Title: Multiple Virtual Directories On the Same Machine - Part 2   
Name: Mark Relly
Date: 2008-04-09 5:33:26 AM
Comment:
Morning Robert,

To supliment my previous post

When the user successfully logs in I add their userDetails object to the session using the code below

USER_SETTINGS_SESSION_KEY is a constant string

HttpContext.Current.Session.Add(USER_SETTINGS_SESSION_KEY, userDetails);

the user is then redirected to the default page

however when I try to retrieve the userDetails from the session

HttpContext.Current.Session[USER_SETTINGS_SESSION_KEY]

they are no longer present and return null.

It appears to only be the code

HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie)
{
oCookie.Path = Request.ApplicationPath.ToLower();
}

that causes this issue

Again many thanks
Title: Multiple Virtual Directories On the Same Machine   
Name: Mark Relly
Date: 2008-04-09 5:08:49 AM
Comment:
Morning Robert,

First of all thanks for the really interesting article.

I've been following it for a time and your first solution worked perfectly for us until we needed to setup a second instance of the site on the same machine.

When we did this users switching between instances were always directed to the session timeout page instead of the login page.

I tried your proposed solution for this (adding the application path to the cookie) but unfortunately this just prevented users from logging in as once they logged in they were automaticaly directed back to the logon page. This is caused because the session seems to lose what is added to the session after it directs away from the login page.

My session start is below:

protected void Session_Start(Object sender, EventArgs e)
{
HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie)
{
oCookie.Path = Request.ApplicationPath.ToLower();
}
string szCookieHeader = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
System.Web.HttpContext.Current.Response.Redirect("~/SessionExpiration.aspx");
}
}
Do you have any ideas?

Your help would be appreciated.

Regards

Mark
Title: Re Stefan   
Name: Robert Boedigheimer
Date: 2008-04-07 12:10:33 PM
Comment:
The timeout detection code for window nbr 2 must be seeing a cookie from window nbr 1 or it wouldn't trip the detection. I would guess that the two are either both virtual directories or share a portion of the DNS name with each other (site1.mysite.com and site2.mysite.com, or www.mysite.com/site1 and www.mysite.com/site2). You will need to adjust the path or domain of your session cookie depending on which it is. In the SessionStart( ) add code like this to BOTH sites so they keep cookies separate (if virtual directories), you must match the case of ALL links or the cookie may not be sent properly, this just converts to all lower.

HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie)
{
oCookie.Path = Request.ApplicationPath.ToLower();
}

You can email me at robertb@aspalliance.com to discuss in more detail.
Title: timeout when clicking link in Outlook   
Name: Stefan
Date: 2008-04-07 9:43:10 AM
Comment:
It seems that sometimes our users get a timeout directly when they shouldn't. Scenario: The user has opened a window (window nbr 1), done some work, but not closed it yet. The user then gets an Outlook email with a link to open a new browser window (window nbr 2, same site). The session for window nbr 1 should not be ended since not more than a minute has passed (we use 20 min setting for session). Most of the times the new window will share session with window nbr 1, but sometimes window nbr 2 gets a new session and it raises a timeout. In those cases it seems that window nbr 2 detects a cookie? Is this happening because of the already opened window nbr 1? Strangely it does not happen very often. What could be causing this behaviour?
Title: session exired   
Name: dayalal patidar
Date: 2008-03-17 2:01:16 AM
Comment:
when click on sinout button then expired my session with cookies in login page and any other
Title: Re: Ameet Ayare   
Name: Robert Boedigheimer
Date: 2008-03-05 8:15:33 AM
Comment:
That sounds very interesting... Can you please email me at robertb@aspalliance.com so I can walk through the specifics in more detail...
Title: Session Variables: Usual behavior   
Name: Ameet Ayare
Date: 2008-03-05 7:39:38 AM
Comment:
Hi, I am using session to pass a lot of data around. I am having a problem on a specific page with these variables!!! I have a gridview on page1(for instance) that writes values to resp. session variables depending on which row was clicked. This begins the user's session. On the redirected page (lets call it Page 2), I use the session variables to extract a particular record from the database. These variables are used on further pages in the same folder. The problem I have is the first time the first page loads, it is holding that data even though when I go back to the gridview page and update the values. I have, on Page1's load event, used session.removeall to make sure that everytime a row is clicked variables are updated. But it is not working. Please help!!!

P.S. Interesting thing is that although page 3 is showing the values of the session variables from the first time the page was visited, further pages show right values.
Title: one more time   
Name: peter gabris
Date: 2008-02-22 9:57:37 PM
Comment:
the url for the free download was left out from my previous message..

http://bsp-software.com/products/TimeoutControl/TimeOutControl.aspx
Title: for lazy people   
Name: Peter Gabris
Date: 2008-02-22 9:55:35 PM
Comment:
Robert: thanks a lot! Your insight helped me to solve my problem and now I can give to all lazy people a ready made control that takes care of the timeout handling.
Title: Re: Al   
Name: Robert Boedigheimer
Date: 2008-02-13 9:08:47 AM
Comment:
I would suspect that the problem with your converted code is that I rely on "short circuiting" in C# where the and operator "&&" does not evaluate the second expression if the first one is false. By default, VB.NET And does not short circuit, instead you need to use AndElse. Anyway, here is my latest recommended code that should be placed in the Session_Start in your global.asax

VB.NET
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
Dim szCookieHeader As String
szCookieHeader = System.Web.HttpContext.Current.Request.Headers("Cookie")
If ((szCookieHeader <> Nothing) AndAlso (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) Then
System.Web.HttpContext.Current.Response.Redirect("sessionTimeout.htm")
End If
End Sub

C#
void Session_Start(object sender, EventArgs e)
{
string szCookieHeader = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
System.Web.HttpContext.Current.Response.Redirect("sessionTimeout.htm");
}
}
Title: Re: Greg   
Name: Robert Boedigheimer
Date: 2008-02-13 7:41:32 AM
Comment:
Can you please email me at robertb@aspalliance.com so we can discuss in more detail?
Title: Always detects timeout on dev web server   
Name: Greg
Date: 2008-02-12 11:25:36 AM
Comment:
I am having trouble with this code constantly detecting a timeout and doing the redirect, even when I set EnableSessionState="true". It works fine in my dev env when run from the file system, but when I deploy it to my test web server it constantly times out.
Title: Not working on all pages   
Name: Al
Date: 2008-02-07 10:00:56 PM
Comment:
Is there anyway to get a VB.NET version of this code, I ran it through a code converter but gave incorrect results. Thanks.
Title: Re: Nagendra Prasad   
Name: Robert Boedigheimer
Date: 2008-01-26 9:28:14 PM
Comment:
I sent you an email with the address listed below with some suggested articles...
Title: Re:Robert Boedigheimer   
Name: Nagendra Prasad
Date: 2008-01-16 6:41:06 AM
Comment:
First of all thanks for your comment(s).
Second i am biggner with asp.net 2.0 so can you provide any example one who handle my Session timeout as well as Detect browser closing through clicks on the [X] button .

It will be very helpfully for me.
Title: Re: Nagendra Prasad   
Name: Robert Boedigheimer
Date: 2008-01-15 9:18:28 AM
Comment:
The first thing I would consider is how important is it to be extremely accurate with the number? If it is not crucial to be "exact", you could just capture the Session_End (assuming you are using InProcess session) and do the work to log them out then. Depending on how long your timeout is and whether you provide a logout link or button (which could be used to abandon the session and update the database). Then you would only be missing a percentage of people that hit the X rather than logout.

A more involved process would be to use client JavaScript and capture the browser closing event, then make a request to the server (AJAX, Web Service, or page) that could do the work as well.
Title: Detect browser closing through clicks on the [X] button   
Name: Nagendra Prasad
Date: 2008-01-15 9:00:32 AM
Comment:
Hi,
I am facing some problem with detecting browser closing through clicks on the [X] button. The session will not be terminated when I click this. My requirement is to show member online with the system or not.
Actually i have to show how many members are online.
for that i am using a flag field in database after login updation with 1 and after logged out with 0.
But if browser closing through clicks on the [X] button by the end user, i am not able to handle it.
Can you please help me regarding this.

Thanks in Advance
Regards
Nagendra
email:wwwnlc111@yahoo.com or wwwnlc111@gamil.com
Title: Re: Kayani   
Name: Robert Boedigheimer
Date: 2008-01-04 7:41:06 AM
Comment:
Can you email me at robertb@aspalliance.com to discuss in more detail? Are you using frames? Does the page use content from multiple domains?
Title: Mr   
Name: Kayani
Date: 2008-01-03 7:07:23 PM
Comment:
Hello Sir,
I have seen one problem in this code, it does not work properly when we have user control on page. I mean I am using it in VS2003 in VB.Net where I have user control in content section. When session expires while redirecting to another page web page gives an error by pointing to one of IDs saved in session such as "Invalid object name tblCusomters", this tblCustomer is not the part of session, it is part of user control and using connection string which is saved in session. Can someone guide me how to solve this problem.
My email address is waqar@kayani-brothers.com
Thanks in advance
Title: Re: Jenny   
Name: Robert Boedigheimer
Date: 2007-12-31 10:23:51 AM
Comment:
I have an article that discusses this at http://aspalliance.com/70 which is appropriate if you only want a single instance of a class stored in session.
Title: How to use classes instead of sessions   
Name: jenny
Date: 2007-12-19 12:31:06 AM
Comment:
hiii.....i want to know how to use a classs for storing a value instead of session and how to call them...im a naive learner and i would b really thankful if u could help me out
Thanks
Jenny :-)
Title: Coordinating Session Timeouts with Forms Authentication Timeouts   
Name: Ivan
Date: 2007-11-30 2:57:14 PM
Comment:
Hi Robert (or anyone who can help with this):

I think there are several articles on the Web trying to address handling Session Timeouts with Forms Authentication timeouts, and coordinating the two.

Here's my scenario:

1) Using .NET 2.0 with Forms Authentication.
2) Persistent cookie is not set. We want our users to log in everytime.
3) Forms authentication timeout is set to use sliding expiration.
4) Session Timeout is InProc.
3) What is the process of writing code to handle and coordinate forms authentication timeouts with session time outs? If both are sliding expirations, is it best to set the Forms authentication timeout to a much larger value, say 8 hours and the session timeout to just 30 mins. Then handle the session timeout as you would have above?

Thanks.

Ivan
Title: Re: LJ   
Name: Robert Boedigheimer
Date: 2007-11-07 8:09:20 AM
Comment:
What you describe should not be a problem for this solution on an initial request because this solution depends entirely on the fact that on an inital request a session cookie should not be present (unless you left a browser open or visited another site and did not set a proper path to isolate your session cookie). With a newly opened browser, and the default non-persistent session cookie, this solution would not find a session cookie in the header of the request. Can you email me at robertb@aspalliance.com so we can discuss in more detail.
Title: Redirects to timeout on first request   
Name: LJ
Date: 2007-11-07 5:23:07 AM
Comment:
Hi,

My application uses Master pages. In the code-behind for a Master page, I access Session variable to determine if the user is logged in or not.

Therefore, every page in my application accesses Session.

So, I have not explicitly set the EnableSessionState in any pages as I believe they all need to be set to true (the default).

The problem is, using this solution to detect Session timeouts results in a timeout being detected upon each initial request.

Does anyone know why this may be?

Can anyone recommend a solution/work around?
Title: Re: Navdeep Bhardwaj   
Name: Robert Boedigheimer
Date: 2007-10-22 7:52:29 AM
Comment:
Please email me at robertb@aspalliance.com so we can discuss in more detail. I assume you are using Forms Authentication and that the authentication ticket is the same for both users.
Title: Cross connection in sessions   
Name: Navdeep Bhardwaj
Date: 2007-10-19 7:29:39 AM
Comment:
Great article, we are having a trouble with our application. We have an application with users having different privileges, when two users with different privileges login from same machine from two different browser windows, after a few clicks we notice that both the browser starts showing the same information. I feel this happens doe to the same cookie name, but what could be a possible solution for such problem if we need different types of users login simultaneously from same machine.
Title: Re: Adreas Reinke   
Name: Robert Boedigheimer
Date: 2007-10-12 10:18:16 AM
Comment:
I was able to reproduce the problem that Andreas was having with an infinite loop. If you want to redirect to a .aspx page (like sessionTimeout.aspx) when a timeout is detected, then you should either have the sessionTimeout.aspx page not derive from the base page class or set a session variable just before you redirect. The problem is that when ASP.NET does the redirect to sessionTimeout.aspx it also was looking for a timeout and Session.IsNewSession() was still returning true. By setting a session variable before the redirect it causes ASP.NET to return false for IsNewSession() and it works as expected.
Title: Re: Adreas Reinke   
Name: Robert Boedigheimer
Date: 2007-10-11 2:11:04 PM
Comment:
We use this solution on several sites with the base class and don't have infinite loops. Do you happen to be redirecting to a .aspx page? Please email me at robertb@aspalliance.com so we can fix the problem.
Title: infinite Loop   
Name: Andreas Reinke
Date: 2007-10-11 1:13:38 PM
Comment:
OK, after some further testing i can say that you will always run into an infinite loop when you try to access the page the first time (and the page you redirect to inherits from this session-timeout-base-class), no matter which browser you are using.
Title: Infinite Loop?   
Name: Andreas Reinke
Date: 2007-10-11 11:29:54 AM
Comment:
Hi,

I get an infinite loop if I try this in Firefox. In IE it works fine. When I change the if-statement to:
HttpCookie lCookie = Request.Cookies.Get("ASP.NET_SessionId");
if (lCookie != null)
{
if(lCookie.Value.Equals(Session.SessionID))
{
Response.Redirect("sessionTimeout.htm");
}
}

it works fine for Firefox but i will get an inifinite loop in IE then.

Has anybody else had this problem?
Title: Re: Juan Zuluaga   
Name: Robert Boedigheimer
Date: 2007-10-09 3:22:57 PM
Comment:
I was able to create the HttpModule and use the code as is, but the catch was I had to put it in the event handler for the PostAcquireRequestState event. If I did it any earlier in the page lifecycle, the session object is always null because it has not been setup yet. Otherwise it worked as expected and detected a timeout just fine. You can email me at robertb@aspalliance.com if you have any other specific questions.
Title: HttpModule implementation?   
Name: Juan Zuluaga
Date: 2007-10-08 5:49:45 PM
Comment:
Great content!

Only one question:
How it can be done with an HttpModule?
I've trying for several hours now, but I can't figure out how to make it work.
Title: Re: Raja   
Name: Robert Boedigheimer
Date: 2007-10-08 10:47:36 AM
Comment:
Simplest example is when you have two pages page1.aspx and page2.aspx, each of which has a code behind file page1.aspx.cs and page2.aspx.cs.

In the Page_Load for page1.aspx.cs put the line:

Session["A"] = 5;

In the Page_Load for page2.aspx.cs put this line:

Response.Write(Session["A"]);

This shows how to set a named session variable in one page and use it in another page.
Title: detail   
Name: raja
Date: 2007-10-05 3:47:45 AM
Comment:
simple example coding in ASP.Net session.
Title: Re: Greg R   
Name: Robert Boedigheimer
Date: 2007-10-03 11:28:09 AM
Comment:
I have not ever heard of AppDomain restarts caused by impersonation before... Can you email me the code (at robertb@aspalliance.com) that you use for the impersonation and I will try it out.
Title: Re: Prabhakaran V   
Name: Robert Boedigheimer
Date: 2007-10-03 11:23:26 AM
Comment:
I think what you are looking for is more of a client side technique for showing a timer and redirecting if not completed (JavaScript, Meta tag, etc). I am guessing you want feedback to the user that it is a particular amount of time left. The session timeout would not provide that type of functionality.
Title: Application Restart   
Name: Greg R
Date: 2007-10-02 10:00:23 AM
Comment:
Thank you for your very informative article.

I have a site where I need to use forms authentication but on one page I need to impersonate a specific Windows users to make a connection. This works but when I go back to one of the other pages nothing works because I have lost my session state. ASP.NET is seeing the change to impersonation as a config change and restarts the application.

I have tried putting that page in a subfolder and putting a web.config file in that subfolder. I have also tried it without the web.config and doing the impersonation in code with the same result. Both ways cause ASP.NET to detect a config change and restarts the application.

Is there anyway that this can be made to work? I have thought about creating a web service to pull the MQ data but it seems like there should be a better way.
Title: time out the page in asp.net   
Name: prabhakaran v
Date: 2007-09-28 9:54:09 AM
Comment:
i am project in asp.net.The name of the project is
"ONLINE EXAM" . Here i need to time out the page in particular time . how can i do it?
Title: Background and How Sessions Are Implemented   
Name: Mathew G
Date: 2007-09-10 4:48:37 AM
Comment:
The article is too tough for me to understand.. i am a beginner in dotnet platform.. can yu explain this topic in a simple way?
Title: Re: Aban   
Name: Robert Boedigheimer
Date: 2007-08-27 8:46:25 AM
Comment:
It sounds like you have two roles on your site (public or private)? The timeout mechanism should be the same for both, at which point you can use whatever role determination you use for other purposes. Please email me at robertb@aspalliance.com if you want to discuss in more detail.
Title: How to get the User Details   
Name: Aban
Date: 2007-08-24 5:23:37 AM
Comment:
Hi,
I have a situation:
Public and Private Users, how can I differentiate who is who on session time out so that I can redirect them accordingly. I using custom authentication and not form level. Also I am not to include state server or sql server mechanism.
Appreciate if u could help me.
Title: sessions   
Name: jameer sd
Date: 2007-08-10 2:46:25 AM
Comment:
good guidance for the davalopers
Title: Define Session period for Loss session   
Name: Rajesh Bhatiya
Date: 2007-08-03 2:47:41 AM
Comment:
It's nice explanation of session and it's nicely working, nut if there is period define for session is well with coding then it is very better.
Title: hi   
Name: hi
Date: 2007-08-01 5:25:38 AM
Comment:
thanks.
Title: Re: B.V.Rajaram   
Name: Robert Boedigheimer
Date: 2007-07-27 5:19:06 PM
Comment:
In general since HTTP is stateless it is not possible to know if the user is done with the site from a server perspective (which is why sessions have timeout values) which is where you would probably need to enforce this type of restriction (because you mentioned "another system"). I have seen techniques where people have added client side code that "pings" the server occassionally to let it know it was still alive (people seem to use this to keep a session alive). You could potentially use such a mechanism each minute and keep a list of who appears to be alive (within a margin of error of a minute) and add a check to your login to ensure they are not still considered "online".
Title: Detect browser closing through clicks on the [X] button   
Name: B.V.Rajaram
Date: 2007-07-27 1:54:00 AM
Comment:
Hi,
I am facing some problem with detecting browser closing through clicks on the [X] button. The session will not be terminated when I click this. My requirement is to show some message when a person login into the same session while it is active in another browser or system. Can you please help me regarding this.

Regards
Rajaram
email:rajphysics@gamil.com
Title: Re: Mike H   
Name: Robert Boedigheimer
Date: 2007-07-10 11:27:52 AM
Comment:
\
Title: More than one dotnet app per server   
Name: Mike H
Date: 2007-07-05 5:06:54 PM
Comment:
Can this method work when you have more than one dotnet application on the server/domain?

The problem I see is that the asp.net_sessionid cookie is the same for all applications. It seems you'd get a false positive on your time out check every time you go to a new application.

FROM MICRO$OFT:
When a user first opens their Web browser and then goes to a Web site that implements ASP.NET session state, a cookie is sent to the browser with the name "ASP.NET_SessionId" and a 20-character value.

When the user browses within the same DNS domain, the Web browser continues to send this cookie to the domain for which it was sourced.

For example, app1.tailspintoys.com and app2.tailspintoys.com are both ASP.NET applications. If the user goes to app1.tailspintoys.com and then goes to app2.tailspintoys.com, both applications would use the same cookie and the same session ID to track the session state of the user within each application. The applications do not share the same session state. The applications only share the session ID.
Title: Re: Andi   
Name: Robert Boedigheimer
Date: 2007-07-03 7:40:43 AM
Comment:
This is one I will need to get more detail on. Can you email me at robertb@aspalliance.com so I can ask you more questions about the situation?
Title: reset session state to default   
Name: andi
Date: 2007-06-29 4:51:25 AM
Comment:
in my application, map data (image file) store in session workspace that set in webconfig file.
When i run my 1stpage, there is no problem with this image, but when i run 2nd page, there is a problem with this image.
because the the image in session is from the 1stpage.
So, how to reset the image session to the very begining state(before i run 1stpage), when i run the 2ndpage.
Title: Re: Suresh   
Name: Robert Boedigheimer
Date: 2007-06-27 7:49:11 AM
Comment:
I don't have any specific experience with trying to close popup windows for a session timeout. Since the request that first notices the timeout has occurred might be in a popup window, the timeout code would need to return JavaScript capable of closing the appropriate windows before doing the redirect. If the popups were always in a specific relationship to each other, at least the server would know which pages would need to be closed. If not, it might be necessary to track the hieararchy in a hidden field that could be passed to the server. I unfortunately don't have any code examples of how this would be done...
Title: Session Expired on Pop-up windows   
Name: Suresh
Date: 2007-06-25 9:14:48 AM
Comment:
In my application some pages will be shown in a popup windows. Assume that the session expired after the popup window has been opened. In this situation the redirect to login page will be open the login page within the popup window itself. Just i want to close the popup window as well as the parent window should be redirected to the login page. The popup window can have 'N' level deep ie Main Window->Popup_1->Popup_2->Popup_3

Kindly share your thoughts/ideas.
Title: Re: Cherukuri.Venkateswarlu   
Name: Robert Boedigheimer
Date: 2007-06-13 8:32:05 AM
Comment:
If you enabled tracing, you can view session variables and values in the output (either in the page or using trace.axd, depending on configuration).
Title: viewing sessions   
Name: Cherukuri.Venkateswarlu
Date: 2007-06-12 11:03:13 AM
Comment:
how can we see session information in server
Title: Re: Sippy   
Name: Robert Boedigheimer
Date: 2007-06-12 9:06:44 AM
Comment:
Cookieless session allows session support without requiring cookies be sent to the user, it instead embeds the session id into the URL of page requests.
Title: Cookieless   
Name: Sippy
Date: 2007-06-08 5:53:53 AM
Comment:
what u mean by cookieless.
Title: Virtual Directories and Applications   
Name: Robert Boedigheimer
Date: 2007-05-18 2:19:39 PM
Comment:
I did some more testing based on Laurent's question about the application path for the cookie and determined that it is very important that the name of a sub-application and the path set for the cookie must be the same case. When I created an application with "App1" but set the path using the ToLower() as shown in earlier comments, the browser did not send the original session cookie and therefore restarted the session. It is important if you have a virtual directory or subdirectory to have all links, the application name, and the cookie path match or there will be problems.
Title: Application path for cookie   
Name: Laurent OLEON
Date: 2007-05-09 8:43:59 AM
Comment:
First thank you very much for your very helpful article, and your kind sense of sharing.
Here's the code i use in session.start :
Dim szCookieHeader As String = System.Web.HttpContext.Current.Request.Headers("Cookie")

If Not IsNothing(szCookieHeader) AndAlso szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0 Then
Dim AppNom As String
Try
AppNom = Request.ApplicationPath.Substring(Request.ApplicationPath.LastIndexOf("/") + 1)
Catch ex As Exception
AppNom = "?Inconnue?"
End Try

Response.Redirect("/Sil_1_2/SessionExpired.aspx?AppURL=" & Request.ApplicationPath & "&AppNom=" & AppNom)
End If

Then I redirect on a generic page when my session times out. It works fine BUT, when i use 2 applications (App1 then 10 minutes later App2), it seems that when App1 times out, App2 times out too. I found in the threads this bit of code I tried to use (even if i don't explicitly use Virtual directories) :
Dim oCookie As HttpCookie = Response.Cookies("ASP.NET_SessionId")
If Not IsNothing(oCookie) Then
oCookie.Path = Request.ApplicationPath.ToLower()
End If

This doesn't work... When I debug I can see on session_start property "path" of the cookie changing to my appPath, but then on each request (without reaching actual timeout), a new session is created, as if ASP.NET won't hear about my "moved" cookie. Any idea ?
Title: Missing part - Recycle worker proces   
Name: Felix Venniker SDB Software Development
Date: 2007-04-19 12:33:54 PM
Comment:
http://blogs.msdn.com/david.wang/archive/2005/09/19/Why_do_I_lose_ASP_Session_State_on_IIS6.aspx

The accompanied URL describes the missing peace of this article, namely the timeout of recycling the worker process. This should be configured as well, otherwise it doesn't work.
Title: Re: Dhana   
Name: Robert Boedigheimer
Date: 2007-04-19 8:02:23 AM
Comment:
I have not used cookieless, but I know that it embeds a session key in the URL. I would use the same basic logic above, and would check that if a new session was just started and the URL already contained a session id, it would be a timeout. I am a little more concerned about the cookieless though, because if someone makes a bookmark to the site and it was included you would get a false timeout.
Title: Doubt   
Name: Dhana
Date: 2007-04-18 2:55:19 AM
Comment:
How to implement this if i use cookieless mode for session state?
Title: Re: Divya   
Name: Robert Boedigheimer
Date: 2007-04-09 9:37:19 AM
Comment:
If you want the session to disappear when the user logs out, you can use Session.Abandon( ) in your logout code and they will be done.

When you hit the back button in a browser by default it shows the previous page from the browser history and not by going back to the web server. If you do not want that to happen, you should setup your .aspx pages to not be cacheable.
Title: sessions   
Name: divya
Date: 2007-04-09 8:01:02 AM
Comment:
Hi,
It would be great if u can solve my problem....I want to make use of session variable such that once a user is logged out....then one cannot go back just by clicking the back button!
Can u plz help!
Title: need help please   
Name: Vishwanath (vishu020@yahoo.co.in)
Date: 2007-03-29 1:36:27 AM
Comment:
Hi.
It was a good one..
Iam a fresher to .net,
and im trying to develop an application...

If a user is logged in, then his session should start and if he logs out then his session should end.
If i click back button on the browser then i should not
view the signed in page of the user who logged out previously.

Please help meou and send reply to my mail id vishu020@yahoo.co.in
Title: Sessions   
Name: babu
Date: 2007-03-26 12:39:21 AM
Comment:
fine,but how to session implement in timeout of session ,error message occur UNABLE TO OPEN VALIDATE DATA
Title: Re: JJ   
Name: Robert Boedigheimer
Date: 2007-02-26 8:27:45 AM
Comment:
Normally that sounds like the timeout value, but other things can also cause session loss (app domain restarts caused by touching web.config or bin folder, IIS recycling, etc). Have you tried to use tracing? It is odd that the viewstate is gone since that is part of the page... It sounds to me like you might be toggling to another web server in a server farm. Is it a cluster? How is persistence handled. Please email me at robertb@aspalliance.com if you want to discuss in more detail.
Title: Questions   
Name: JJ
Date: 2007-02-23 5:37:18 PM
Comment:
The web application I am working on works fine except after the page is idled for 5 minutes or more , the page would postback as if it is being loaded and accessed for the first time, clearing the sessions and viewstates. I checked the session property and it is set by default for 20 minutes. So I'm not sure where that 5 minutes timeframe came from. I am wondering if this have anything to do with session timeout ? Any suggestion will help. thanks!
Title: Re: Jonathan   
Name: Robert Boedigheimer
Date: 2007-02-20 8:07:47 AM
Comment:
The solution is based on the use of cookies to detect the situation where a session existed before (can only really tell by the cookie) and yet a new session was created. If you can't count on cookies, you have lots of other problems because you have no way of knowing on an individual request whether that person had a session before. Using things such as IP address are difficult because of proxy servers, etc. Unfortunately, without cookies the approach I have taken simply won't work.
Title: If you remove the cookies...   
Name: Jonathan
Date: 2007-02-16 7:03:26 PM
Comment:
Hi, If you test this by removing the cookies sometime during the navigation of your site (which could easily happen in the real world), then the

"If Not IsNothing(Request.Headers("Cookie")) And Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0"

does not get triggered, therefore a new session is not created. Then, when you access one of your Session variables, you get the "Object not set..." error... Any idea?
Title: Timeouts   
Name: Parshuram Shinde
Date: 2007-02-16 5:25:55 AM
Comment:
It is very Good article. So helpful
Title: Too good   
Name: amrita
Date: 2007-02-09 8:43:21 AM
Comment:
very help ful, concise but informative.
Title: super   
Name: saravanan
Date: 2007-02-06 2:48:14 PM
Comment:
this is a super article fro session
Title: Re: Vasanth   
Name: Robert Boedigheimer
Date: 2007-01-23 8:27:56 PM
Comment:
No, ASP and ASP.NET do not share sessions
Title: Sessions On ASP and ASP.Net   
Name: Vasanth
Date: 2007-01-11 7:54:19 AM
Comment:
Can use Session Created in .asp file same in .aspx file
Title: Re: Joe Beam   
Name: Robert Boedigheimer
Date: 2007-01-04 12:49:45 PM
Comment:
That actually would not work because the Session_End (which only works for in-process session) will fire independent of any client request, so there is no one to redirect... The last request that was done on the site by the user received its response, then the session timeout limit is hit, the event fires and there is no active request from the user for a response to go to
Title: Would this work   
Name: Joe Beam
Date: 2007-01-04 12:11:39 PM
Comment:
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)

If Request.IsAuthenticated Then
'session timed out on authenticated user
Response.Redirect("login.aspx")
End If
End Sub

Any thoughts on this technique?
Title: Nice and Useful for cookie sessions   
Name: Nitin Shende
Date: 2007-01-04 1:22:44 AM
Comment:
This is wonderful article for users. By using this approach we have make the application easier.

Thanx for that.........
Title: Session expires in first access....   
Name: Rodrigo - rodrigoszn@gmail.com
Date: 2006-12-14 1:18:57 PM
Comment:
Hi can one help me!?!?
Recently here in my work we added the following code in the Global.asax file to handled the session expired and redirect users to the home of the site explaining them the occurred (some thing like "Your session has expired, please restart your navigation.").

public void Session_Start(Object sender, EventArgs e)
{
if(Session.IsNewSession && Request.Headers["Cookie"] != null && Request.Headers["Cookie"].IndexOf("ASP.NET_SessionId") >= 0)
{
Response.Redirect("/index.aspx?timeout=1");
//when the param "timeout" exists in the url the user
//receives the message "... Session expired ..."
}
}
In our tests the code above works fine, but now sometimes we open the browser, type the url address of the site and the message "... session expired ..." appears. This occurs just in some machines and not all the times we access the site.
Someone knows what is happening??
Thanks a lot
Rodrigo
Title: Re: Sompop   
Name: Robert Boedigheimer
Date: 2006-11-29 7:57:52 AM
Comment:
Is your session timeout page a .htm or at least in a folder that is publicly accessible? When you redirect to the page to show the timeout has occurred, how do you send them back to the login page? By default, ASP.NET Forms Authentication will see a request for a secure page and will add the URL for that page in the ReturnUrl querystring parameter to your login page. The login page redirects back by using that parameter. If you are manually redirecting the user to the login page from your session timeout page, make sure you are not including that querystring parameter. You can also email me at robertb@aspalliance.com so we can discuss in more detail if you would like.
Title: Transfer to defaul.aspx after login   
Name: Sompop
Date: 2006-11-28 2:31:52 PM
Comment:
Thank you very much for ur comments. I actually tried and changed something like you and other comments said and it works without using global.aspx. My next question is that Say after timeout, it goes to session timeout page to notify users. After that, they go to login page. After they login, they go to session timeout page again according to FormsAuthentication.RedirectFromLoginPage of login control. I want it to go to default page if it came from session timeout page. How could I do that? I'm appreciated for the first answer. Thank you again
Title: Re: bruce cartland   
Name: Robert Boedigheimer
Date: 2006-11-27 10:56:36 PM
Comment:
Do you have virtual directories for your web sites? Are they "application roots" in IIS? Can you email me some more details about your setup so I can try to reproduce this?
Title: Re: Sompop   
Name: Robert Boedigheimer
Date: 2006-11-27 10:45:16 PM
Comment:
I have been refining the method used, and have this alternative implementation. Just add the following to the global.asax.cs (replace any existing implementation of Session_Start):

void Session_Start(object sender, EventArgs e)
{
//A new session is being created, but if a session cookie was sent with the request
// it must be a timeout situation

//It appears from testing that the Request and Response both share the
// same cookie collection. If I set a cookie myself in the Reponse, it is
// also immediately visible to the Request collection. This just means that
// since the ASP.Net_SessionID cookie is set in the Session HTTPModule (which
// has already run), that we can't use our own code to see if the cookie was
// actually sent by the agent with the request using the collection. Instead
// use the Headers to get all of the cookies in a string and search for the session id
// cookie name
string szCookieHeader = System.Web.HttpContext.Current.Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
System.Web.HttpContext.Current.Response.Redirect("/sessions/sessionTimeout.htm");
}
}
Title: How to implement this concept to the real code   
Name: Sompop
Date: 2006-11-27 1:21:52 PM
Comment:
Hi Robert,
I would like to ask you about session timeout after I read your article on http://aspalliance.com/520
I'm still a beginner, so I don't understand how to do this but i really need it for my job.

1. How do I implement the basePageSessionExpire.cs class
* Do I have to add new item => class and copy your code? If not what would I do?
2. Say I have a default.aspx with 1 minute session timeout (I changed to 1 minute on web.config)
Where (on the default.aspx) do I put the class that I just created to determine whether or not the session times out. If I understand wrong, what would I do to check session times out on the page I want or every page?
Title: problem related to session state   
Name: Preetam jain
Date: 2006-11-27 5:10:17 AM
Comment:
hello, may be you can help me.. i have a problem ,i want to set LoginStatus of user equal to N in database when session is expired of particular user ...
can you explain and email me at preetamjain@gmail.com
thank
Title: Modifying cookie path   
Name: bruce cartland
Date: 2006-11-21 6:50:53 PM
Comment:
Great article - short, concise, very useful.

You say to put in Session_Start
HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie) oCookie.Path = Request.ApplicationPath.ToLower();

I am puzzled as to why this works for others. When I do it resetting the path causes the session to be "renewed" and Session_Start will be called again on the next request. This results in a new session for every request (with everything cleared of course).

So I put it in Application_BeginRequest. Everything now works properly and Session_Start only gets called once.
Title: Re: Melissa   
Name: Robert Boedigheimer
Date: 2006-11-15 11:22:17 PM
Comment:
I don't believe that Session.Abandon clears the session cookie (I thought on normal sessions it just removes the memory used for the session). Do you completely close all of the browser instances or just a specific window? I think it will probably be easier if you just want to send me an email at robertb@aspalliance.com and we can discuss further.
Title: Index of Cookie not being cleared   
Name: Melissa
Date: 2006-11-15 11:52:33 AM
Comment:
Hi Robert,

thanks for the great article. i have implemented this in our asp.net site, but there's one problem i'm still having:

Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") is not always getting cleared after I call session.abandon and the browser window is closed.

If the same user tries to log back in, it will force them to the timout page for a long time (up to 15 mintues, at least). I believe it's because the index of the "ASP.NET_SessionId" in the cookie is still set above -1. Also, I've noticed that the IndexOf("ASP.NET_SessionId") is always the same for each individual user. (not sure if that's normal, or if it indicates some kind of configuration problem).

any insight would be helpful. thanks again for the article.

-Melissa
Title: Re: Greg K   
Name: Robert Boedigheimer
Date: 2006-10-19 11:23:18 AM
Comment:
The reason you would use that piece of code is when you have multiple virtual directories under a single domain name or web site. If you don't set the path for the session cookie, it defaults to a path of "/". So if you have two virtual directory based sites WebApp1 and WebApp2, if you visited an .aspx page on WebApp1 you would get a session cookie with a path of "/". If you then go to a page on WebApp2, the code above would see a new session started (which is true), but it also sees the cookie for WebApp1 because the path was "/". By setting the path as you showed, your cookie for WebApp1 would have a path of "/webapp1" so when you go to WebApp2 that cookie would not be sent. If you are not in that situation, then don't include that code.

If you still need that code and want more direct assistance, just email me at robertb@aspalliance.com so we can discuss in more detail.
Title: Modifying Cookie Path   
Name: Greg K
Date: 2006-10-19 10:50:27 AM
Comment:
Robert,

When I use this:
HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie)
{
oCookie.Path = Request.ApplicationPath.ToLower();
}
it works on 4 out of 5 servers. If I take it out, then it works on the 5th one.

On the server that it doesn't work on, there is only one default web site, with other virtual directories in it. I can't give you a good error since my application redirects to an error page indicating that the user doesn't have permission to see the page.

The conditional code looks at a Session variable that gets first populated on the initial page. I then go to an admin page (where the Session variable is checked) and thats when it comes up empty and I get redirected.

Any ideas why it wouldn't work on the one server? I have to think it is caused by some setting but can't verify. I'm also a bit confused by the description of why I would need to use this - is it just for multiple web sites on the same server?

Thanks,
Greg
Title: Re: buf   
Name: Robert Boedigheimer
Date: 2006-10-12 8:07:38 AM
Comment:
The sessionTimeout.htm is any page that you want to create that explains to the user that a timeout has occurred. You can create a file with a different name, or even take a different action for your site if that makes sense. The article is more about how to detect that a session timeout has occurred, than how to deal with it once it does (which may be very site specific).
Title: good   
Name: buf
Date: 2006-10-12 3:52:49 AM
Comment:
very nice,what is sessionTimeout.htm
Title: Re: Rod   
Name: Robert Boedigheimer
Date: 2006-09-25 8:42:26 AM
Comment:
The current user count is always an estimate because the web is "connection-less". The session mechanism uses a timeout mechanism to deal with the fact that it does not know explicitly when someone is done using a particular site (unless you have an explicit logoff and they choose to use it). Since you mentioned that you are using ASP.NET 2.0, you could use the Membership.GetNumberOfUsersOnline() which provides an estimate of the number currently using the site.
Title: do you have a user count?   
Name: rod
Date: 2006-09-22 9:26:23 AM
Comment:
do you have an example for showing who is currently logged in? the session timeout is close...
for background:
web application: c# .net 2.0
authentication: windows against active directory 2003
i need to know the number of users currently logged in but kerberos flows it through...so what to do?
Title: Application Analyst   
Name: Abdullah AlSubaiee
Date: 2006-09-12 3:53:40 AM
Comment:
It is a great article and helpful discuss
Mr.Robert really thank you a lot
Title: It helps me much   
Name: zelalem
Date: 2006-08-27 4:35:07 AM
Comment:
It is nice! I got all what i need!

It is cute for cookie and session users.
Title: For the subweb in the main web app   
Name: mingming
Date: 2006-08-08 4:22:46 PM
Comment:
How to make the sub web app session time out work in the main web app
Title: Good one   
Name: Nitin
Date: 2006-08-07 1:35:06 PM
Comment:
good article
Title: Re: pd   
Name: Robert Boedigheimer
Date: 2006-07-27 11:01:26 AM
Comment:
It would not be odd for the Request.Headers["Cookie"] to be null on the first request (if you don't use any cookies yourself, the session cookie would not be present on the first request). Are you using cookieless sessions? Is this at least the 2nd request?
Title: Request.Headers["Cookie"] returns null   
Name: pd
Date: 2006-07-27 8:47:45 AM
Comment:
Hi
I tried the above code,while debugging I got the value of Request.Headers["Cookie"] as null.Hence its not entering to the if block & couldn't redirect to the SessionTimeOut page.Please suggest me what to do for this.
thanks
pd
Title: Re: Bob   
Name: Robert Boedigheimer
Date: 2006-07-11 9:40:07 AM
Comment:
I tried to duplicate the problem you are having (I was using VS 2003/ASP.NET 1.1) and was not able to. I requested a page, then waited for a timeout, hit a button on the page which caused a postback and the timeout detection code to run and redirect the user. If I immediately type an address for a page on the site, it works without saying it timed out. The reason that it does this is because the request made that checked the timeout created a new session, and on the subsequent requests the IsNewSession will not be true. Please email me at robertb@aspalliance.com if you want me to look more at specifically what you are doing.

A quick suggestion would be to set a session variable in your login page to ensure it creates a new session and that the next request won't see IsNewSession as true.
Title: re: Question   
Name: phil
Date: 2006-07-07 9:58:07 AM
Comment:
did you try a session.clear(); think that will do the trick...
Title: Question   
Name: bob
Date: 2006-07-06 6:24:25 PM
Comment:
How can I modify this code so that when the session expires a user and login from the redirected page. I have it currently redirecting to a log in page but it will not let the user log in because it still finds the expired session. All is well if I close the browser and log in again....

Thanks
Title: Re: John Dahl   
Name: Robert Boedigheimer
Date: 2006-06-20 12:43:01 PM
Comment:
1. Is the timeout you are setting for the Forms Authentiction or the session timeout? Do you run in a web farm and are possibly changing physical servers?

2. I am not aware of a setting that allows you to programmatically enable session from within page code (I believe the session support is in an HttpModule that runs before the handler for the page).

3. The way you currently have it coded I am not sure if a page that has disabled session state would still be redirected. In my original the check of Context.Session != null seemed to indicate if the state was enabled. I included that so that pages that disabled session state would not be impacted.

If you want to walk through options/issues in more detail go ahead an email me at robertb@aspalliance.com.
Title: Redirecting to timeout page unusually   
Name: John Dahl
Date: 2006-06-12 5:45:29 AM
Comment:
Quite a good article.
I have used the code in following form.

protected void Session_Start(Object sender, EventArgs e)
{
//this will make the cookie work even in sub domains
HttpCookie cookie = Request.Headers["Cookie"] ;
if (cookie != null)
cookie.Path = Request.ApplicationPath.ToLower();

//Algorithm: If cookies are present but new session is initiated
//that means session time out has occured

if( Session.IsNewSession)
{
if( null != Request.Headers["Cookie"]
&& Request.Headers["Cookie"].IndexOf(FormsAuthentication.FormsCookieName) >= 0)
{
if(User.Identity.IsAuthenticated)
FormsAuthentication.SignOut();

string redirectPath = "login.aspx";

Server.Transfer(redirectPath);
}
}

}

However I have 2 problems.
1) The user is redirected to the login page unusually. I have put 30 mins of timout. But the redirection happen even after a min of browsing a page. This behaviour is not consistent and making me crazy.

2) I have a page which don't need to use the session and session timeout has no effect on it. But it hosts a usercontrol(which is loaded dynamically upon certain condition). So when the usercontrol comes into effect, I need to use the session. Is there any way to programmatically enabling the page session state.

And again, will disabling the session state in a page make the page unaffected from session timeout redirection?

Please help.
Title: Re: Javier   
Name: Robert Boedigheimer
Date: 2006-06-05 7:58:59 AM
Comment:
Assuming that you are using the default in-process session, once it times out on the server the session memory is reclaimed by ASP.NET and you will not be able to retrieve it. The other options would be to store the database row key information in a non-persistent cookie and use the timeout logic to trigger calling the database with the cookie info to delete the row. Another option would be to use the SQL Server storage for the session rather than manage your own database row. Then all of you session information would automatically be in the database, and there is a process that cleans up old sessions in SQL Server. If you need more specific advice, feel free to email me at robertb@aspalliance.com.
Title: Nice but   
Name: Javier
Date: 2006-06-03 1:10:29 PM
Comment:
Nice post, but my problem is as follows: in my application if a user logs in successfully, a session variable is created with his data and a row is created in a table in the DB using this data. When the user logs out, this row is deleted. SO, if a timeout arises, how can access to the session variable to get user's data to delete the appropiate row on DB??

Thanks in advance,
Javier.
Title: sessions   
Name: paraveen
Date: 2006-05-19 6:29:13 AM
Comment:
its very useful for who doesn't know about sessions.if this sessions explian with any examples user can understand easily.
Title: Re: Hope   
Name: Robert Boedigheimer
Date: 2006-04-04 3:46:23 PM
Comment:
The session timeout is stored in the "sessionState" element in the web.config (or the server's machine.config if it is not present in the local web.config). It defaults to 20 minutes
Title: Re: Hocus Pocus   
Name: Robert Boedigheimer
Date: 2006-04-04 3:44:49 PM
Comment:
The default session state timeout is stored in the "sessionState" element, it should be 20 minutes.
Title: Re: rvmpk   
Name: Robert Boedigheimer
Date: 2006-04-04 3:43:42 PM
Comment:
Please email me more details at robertb@aspalliance.com. What specifically does not work about them?
Title: Where is the settings?   
Name: Hope
Date: 2006-04-03 6:16:38 PM
Comment:
I have a Windows2003 test server and a Windows2003 production server. I have put the same source files in a virtual directory of both the servers. However, with no activity, the test server session times out after 20 mins and the production server session times out after 60 mins. My question is how/where do I find this settings?
Title: Is this where the default session timeout is stored?   
Name: Hocus Pocus
Date: 2006-04-03 2:47:51 PM
Comment:
Go to "ApplicationPool" -> Your application pool.
Go to "Properties" -> "Performance" tab.
See value in "Shutdown worker processes after being idle for (time in minutes)"
- Is this where the default session timeout is stored?
Title: This does not work with HTTP modules   
Name: rvmpk
Date: 2006-04-03 1:38:36 PM
Comment:
This checking time out logic does not work if you are using HTTP modules. Do you have any suggestions?
Title: Solution for Pankaj's problem   
Name: Tsvetomir Tsonev
Date: 2006-04-02 11:11:05 AM
Comment:
In order for the login process to work, your login page must not inherit from the base page, that contains the session timeout checking code.

Otherwise a loop occurs, as you've noted.
Title: BasePage code always kicks in.   
Name: Pankaj
Date: 2006-04-01 9:34:36 PM
Comment:
Thanks for the great article.

The following VB.net version works pretty good. But, I am facing one slight issue. Once the user sign out from secured page, I redirect them to home.aspx page, which inherits BasePage.vb . The following code again kicks in and I get redirected to "SessionTimedOut.aspx" instead "home.aspx"

Can someone please suggest how can I avoid this?

BasePage.vb Code start-----------
If Not Context.Session Is Nothing Then

If Session.IsNewSession Then

Dim sCookieHeader As String = Convert.ToString(Request.Headers("Cookie"))
If Not sCookieHeader Is Nothing AndAlso sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0 Then
If Request.IsAuthenticated Then
FormsAuthentication.SignOut()
End If

Response.Redirect("SessionTimedOut.aspx")
End If
End If
End If
BasePage.vb Code end-----------

Thanks

Pankaj
Title: Re: Raúl   
Name: Robert Boedigheimer
Date: 2006-03-29 9:38:20 AM
Comment:
Can you email me at robertb@aspalliance.com? I will need to walk through some other questions with you that will be easier via email. Thanks!
Title: Null reference.-   
Name: Raúl
Date: 2006-03-29 8:32:53 AM
Comment:
Hi, maybe you can help with a little problem I am having...My session seems to expire automaticly and I loose all the variables stored there. I checked out the time out in the webconfig. but is fine. But the real problem is that it works fine on my pc...but when I upload it to the develompent server it crashes.
Title: Excellent   
Name: Krishna Kiran
Date: 2006-03-23 10:23:41 AM
Comment:
Hi Robert,
Iam very thankful to U.I placed the code in session_start,it is working. (as told by asp.devnull).
Thanks to both of U.
Regards Kiran.
Title: Session related problems   
Name: Ashish Upadhyay
Date: 2006-03-20 11:58:06 PM
Comment:
Sub Session_Start(...)

If Session.IsNewSession Then

If Not IsNothing(Request.Headers("Cookie")) And Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
Response.redirect("timeout.htm")
End If

End If

End Sub

This code ends the browser session, I want to close the user session.

Can I make home page as a .aspx page, even there is no need of server side response?

When does a user session start?

How to close a particular user session?

Can i call Session.Abandon() to close user session?

Please get back reply to above question.

Ashish Upadhyay
ashish_upadhyay76@yahoo.co.in
Title: Re: Ricky   
Name: Robert Boedigheimer
Date: 2006-03-10 7:34:58 AM
Comment:
I got an initial email from you and responded, but have not heard from you about this issue... I am guessing the applet problem is related to your use of cookieless sessions?
Title: session causes applet to reload?   
Name: Ricky
Date: 2006-03-06 9:20:03 PM
Comment:
Hi Robert,

Thanks a lot for your help. I have sent an email to your stated address; see if you need further details.

Thanks again and looking forward to your valuable advice and comments
Title: Re: Ricky   
Name: Robert Boedigheimer
Date: 2006-03-03 8:34:56 AM
Comment:
Can you please email me at robertb@aspalliance.com so we can discuss in more detail?
Title: session causes applet to reload?   
Name: Ricky
Date: 2006-03-03 6:43:55 AM
Comment:
Thanks for the great article. But we got one problem

We are implementing a web page on .NET, in which we have a few applets for the end users to download. But we find an issue that the applets kept being reload even there are no changes on the applets (java codes). We are told that the session mgt is the "root cause" of this reload

"...As you can see from the captured creen "sessionid.JPG", the pages are all under an URL with a session id. This session id is DIFFERENT each time you login into the account. Therefore the URL is DIFFERENT each time you login into the account also. From our findings, the browser would download the .cab/.jar files every time if the URL is different. So there is no resolution to this issue".

Any advice / comment ? Thanks a lot

Therefore, there may be no feasible solution to this issue.
Title: Re: Dave   
Name: Robert Boedigheimer
Date: 2006-02-17 4:39:37 PM
Comment:
Can you email me at robertb@aspalliance.com so I can get more details from you?
Title: String thing when I use your code   
Name: dave
Date: 2006-02-17 4:24:29 PM
Comment:
Hi, Robert,
Thanks for the great article.
However, when I tested it, "(Session.IsNewSession)" always returned true even after the session object did timeout. This means it never went into the block to redirect to other page. Can you analyze why I got this.
Title: Thank you!   
Name: Laura Monge
Date: 2006-02-15 2:29:21 PM
Comment:
I want to thank you for this article. I clears everything out and it really helps. The other solutions that I found, even in the msdn site were useless.
Title: Re: Re: Rick Cohen   
Name: Niels Proost
Date: 2006-02-09 2:55:21 AM
Comment:
Robert, it's more than a year ago you added your suggestion to add the applicationpath to the cookie in the global.asax Session_Start, but I could kiss you! We had a mayor issue with this and now.... PERFECT! Thanks a lot for sharing!
Title: Re: Mark J   
Name: Robert Boedigheimer
Date: 2006-01-31 9:18:12 AM
Comment:
Since you have a very specific situation the solution that you show may work fine. In general the problem with just using a specific session variable alone is that it will fail on a first request to the site (since the session variable will also be missing). Since you have a single page site and are checking only on a postback it would presumably only fail when a first request is a POST (which would not be a "normal" situation).
Title: Alternative?   
Name: Mark J
Date: 2006-01-30 2:28:22 PM
Comment:
Now, one problem I have, is that I am using a cookieless(=true) session, and also, my website is "one page based" (default.aspx). Here is an alternative I have found. Is there something wrong with that? Thank's again for your help and for this web site, it helps me a lot to learn ASP.Net!

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
Session.Add("SessionIsUp", "True");
}
else
{
//Check if a timeout occured
if (Session["SessionIsUp"] == null)
{
Response.Redirect("timeout.htm");
}
}
}

Thank you!

Mark J
Title: Alternative?   
Name: Mark J
Date: 2006-01-30 2:11:57 PM
Comment:
Now, how about this solution.

private void Page_Load(object sender, System.EventArgs e)
{
Session.Add("strUserOB", strUserOB);
Title: Thanks!   
Name: Mark J
Date: 2006-01-30 1:50:25 PM
Comment:
Thank you Robert for the Heads up!
Title: Re: Mark J   
Name: Robert Boedigheimer
Date: 2006-01-27 3:34:48 PM
Comment:
Since the Application object is shared by all users on a server, setting a variable in Application will affect all users on the site. If a given user does not make a request up until his/her session timeout occurs, the Session_OnEnd will fire and you set the "global" variable. The next user (not necessarily the one that had a timeout) who asks for default.aspx will get redirected incorrectly to the timeout page.
Title: Why not in application?   
Name: Mark J
Date: 2006-01-27 2:30:13 PM
Comment:
Is there something wrong with the way that I am doing it, which works fine by the way. It seams to be much more simple then any of the example I've seen and it works as fine with cookie sessions or not. I'm quite new to ASP.Net so perhaps someone could prove me wrong. Thanks guys...

Global.asax:
protected void Session_End(Object sender, EventArgs e)
{
Application.Add("Timeout", "true");
}

Default.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
{
if(Application["Timeout"] != null)
{
Application.Remove("Timeout");
Response.Redirect("timeout.htm");
}
}
Title: Re: Raphael   
Name: Robert Boedigheimer
Date: 2006-01-24 8:22:51 AM
Comment:
The Session_OnEnd will fire (only for in-process session storage) independent of any page request. That will not help you determine when the next request arrives from the given user whether his or her session is still alive. This solution provides the ability to determine on a given request whether the user previously had an active session that is now gone.
Title: Session_End   
Name: Raphael
Date: 2006-01-20 2:29:05 PM
Comment:
Can't I rely on the application's Session_End to know when a session times out or is logged out?
Title: Re: tcoogle   
Name: Robert Boedigheimer
Date: 2006-01-03 9:20:34 AM
Comment:
I am not sure why the IsNewSession would not be working for you when using SQL Server for the session storage. I have not tested it with SQL Server.
Title: SQLServer vs InProc   
Name: tcoogle
Date: 2005-12-30 4:32:34 PM
Comment:
Is the timeout handled differently when using SQLServer for session state as opposed to using InProc? The above code works great when I am using InProc but when using SQLServer the Session.IsNewSession always returns false. Note: This was testing with 1 minute timeout. I tried with longer, but got same result.
Title: So, I Learned Something   
Name: Dean L
Date: 2005-12-08 8:48:07 PM
Comment:
This is a great article.

I did run in to a self induced problem. I have a project that uses Forms Authentication. Being inpatient, I set the timeout for 1 minute for testing purposes. I then started testing, but it didn't work because the IsNewSession was always returning False. What I discovered after some research is, there is another timeout that needs to get adjusted. It is the sessionState timeout further down in the Web.Config. Essentially what I learned is to keep these values the same or weird things start happening.
Title: For those of us that are VB.NET   
Name: Michael Rogers
Date: 2005-11-16 2:58:13 AM
Comment:
This is for those VB.NET people that need this functinality (like I did) for their base class.



Imports System.Web.Security

Public Class BaseForm
Inherits System.Web.UI.Page

Protected Overrides Sub OnInit(ByVal e As EventArgs)
MyBase.OnInit(e)

If Not (context.Session Is DBNull.Value) Then
If Session.IsNewSession Then
Dim strCookieHeader = Request.Headers("Cookie")
If Not (strCookieHeader Is DBNull.Value) And strCookieHeader.indexof("ASP.NET_SessionId") > 0 Then
If Request.IsAuthenticated Then
FormsAuthentication.SignOut()
End If
Response.Redirect("Logon.aspx")
End If
End If


End If
End Sub

End Class
Title: Wonderful!!   
Name: Subrahmanyam K
Date: 2005-11-08 9:20:05 PM
Comment:
This was an easiest and very useful article in detecting Session Expiration.
For many days i was trying how to achieve this.
At last I achieved what i want.

Thanks a lot.
Title: Great Article and comments   
Name: John V
Date: 2005-10-06 4:27:49 PM
Comment:
Hey, great article. I seached high and low for this information. Two comments: (1) You'd think this information would be easier to find in MS documentation, and (2) It should be much simpler in an ASP.NET application to hook and handle such a common event as session timeout.
Title: Re: Tony Cooper   
Name: Robert Boedigheimer
Date: 2005-09-29 9:36:37 AM
Comment:
I have seen that on several occasions when using base pages (which is a pretty typical best practice these days). I created the .cs file as indicated in the article and created a basic page (VS 2003) with a textbox and button. I can still go into design view while deriving from the base page. Can you try a simple page like that and see if it works? We can dialog about it more directly if you want to email me at robertb@aspalliance.com
Title: Nice code but...   
Name: Tony Cooper
Date: 2005-09-27 11:18:09 AM
Comment:
Robert,
Just what I was looking for, great. So I've put this code in it's own class and inherit that on all my forms. Now when I try to load the forms in VS.NET designer I get the following message: "The designer could not be shown for this file because none of the classes within it can be designed"
Changing the inherits back to System.Web.UI.Page loads fine. Of course I forgett to change it back.

Any help?

Tony
Title: Great   
Name: shantha Buddhika
Date: 2005-08-31 3:23:17 AM
Comment:
This is a great artical about session and cookies. Important thing is this explains session and cookies in simple and understandable format. So I would like to thank
Robert Boedigheimer
Title: coooooooool   
Name: santosh
Date: 2005-08-10 9:23:18 AM
Comment:
cooool one..thnks
Title: Thanks   
Name: Tony Cooper
Date: 2005-08-06 4:59:54 PM
Comment:
Robert, great article and examples. Just the thing I've been looking for. Works great

Thanks
Title: Excellent Article!   
Name: Peter Ingraham
Date: 2005-08-03 11:46:04 AM
Comment:
Excellent article and additional comments. It was just what I was looking for. Fortunately, I had already implemented a base class for my aspx pages.
Title: RE: Pree   
Name: Robert Boedigheimer
Date: 2005-08-01 8:00:32 AM
Comment:
The exception "Object reference not set to an instance of an object" occurs when you have a reference type that does not presently point to an object. The example from this article was referencing a session variable either before it was set or after the session expired. If I placed a dataset into session and then used ((DataSet)Session["CUSTOMER_DATA"]).Tables["CUSTOMER"] after the session expired I would get that exception because the DataSet reference would be null.

This is a very generic problem in ASP.Net, so to find it you will need to use debugging and instrumentation to locate the line that is causing the problem.
Title: its not i asked   
Name: Pree
Date: 2005-08-01 7:39:46 AM
Comment:
When exactly the server error occurs as "Object reference not set to an instance of an object" in ASP.NET?
Title: Deadly Article   
Name: Mrugesh Doss
Date: 2005-06-09 11:49:23 AM
Comment:
Deadly article sir. Thank you very much.
Title: Nice   
Name: Ram
Date: 2005-04-26 4:15:32 PM
Comment:
Nice article!
Title: mike..   
Name: Lee
Date: 2005-04-07 4:23:51 PM
Comment:
The intention is to ensure that if the session expires then any authenticated user is logged-out to prevent the situation where you're still authenticated but all your session variables have disappeared.

It was intended for a site where, at the time, all pages required authentication.

Now the site is no longer all https and I've also adopted a slightly modifed version of Robert's original post, which seems to work nicely :)

override protected void OnInit(EventArgs e) {
base.OnInit(e);

if (Context.Session != null) {

if (Session.IsNewSession) {
string strCookieHeader = Request.Headers ["Cookie"];

if (
(null != strCookieHeader) &&
(strCookieHeader.IndexOf ("ASP.NET_SessionId") >= 0)
) {
// If there's an authenticated user, log them out
//
if (Request.IsAuthenticated) {
FormsAuthentication.SignOut ();
}

Response.Redirect (PAGE_NAME__SESSION_TIMEOUT);
}
}
}
}
Title: Neither will this code!!   
Name: Mike
Date: 2005-04-06 9:36:58 PM
Comment:
Lee... tried your code as I need to handle both situations (where a user may or may nor be logged in) but it still doesn't work for me as you listed it above.

Can you explain what it's meant to do as I can't see the logic in it.. it only seems to redirect if the authentication ticket is set - so if a user is not logged in it will never get to the Server.Transfer().

Perhaps I'm missing something obvious but I'veplayed with it and can't get that way to work at all...

Mike
Title: Correction   
Name: Lee
Date: 2005-04-06 1:48:18 PM
Comment:
The previous code won't work.

protected void Application_AcquireRequestState (
Object sender, EventArgs e
) {
if (Session [SESSION_KEY__SESSION_STATE_EXISTS] == null) {
// The 'session state exists' variable doesn't exist
//
if (User.Identity.IsAuthenticated) {
// If there's a user logged-in, log them out
//
FormsAuthentication.SignOut ();

Server.Transfer ("~/SessionTimeout.aspx", false);
}
else {
// Otherwise add the 'session state exists' variable
Session [SESSION_KEY__SESSION_STATE_EXISTS] = true;
}
}
}
Title: How about this?   
Name: Lee
Date: 2005-04-04 9:34:27 PM
Comment:
protected void Application_AcquireRequestState (
Object sender, EventArgs e
) {
if (Session [SESSION_KEY__SESSION_STATE_EXISTS] == null) {
// The 'session state exists' variable doesn't exist
//
if (User.Identity.IsAuthenticated) {
// If there's a user logged-in, log them out
//
FormsAuthentication.SignOut ();

// Remove UserData from SessionState
//
Session.Remove (Page_Base.SESSION_KEY__USER);

Response.Redirect (Page_Base.UrlBase, false);
}
else {
// Otherwise add the 'session state exists' variable
Session [SESSION_KEY__SESSION_STATE_EXISTS] = true;
}
}
}
Title: .   
Name: Lee
Date: 2005-04-04 9:26:40 PM
Comment:
A masterpiece of clarity.

Thanks :)
Title: RE: Vijay BK   
Name: Robert Boedigheimer
Date: 2005-02-28 10:48:10 AM
Comment:
The count can tell you how many items you currently have in Session, but I don't know how that would help you detect a timeout... You can see that the count is now 0, but is that because you have not put anything in session yet or because it expired?
Title: Session TimeOut   
Name: Vijay BK
Date: 2005-02-26 1:05:15 AM
Comment:
Can we check with the Session.Count Collection of the Session Object to check whether the Session has expired or not.
Title: Re: Rick Cohen   
Name: Robert Boedigheimer
Date: 2005-01-25 9:53:03 AM
Comment:
I have had several readers that had problems with the solution when they have multiple web sites hosted in virtual directories. From testing I noticed that the ASP.NET_SessionId cookie has a default path of "/" which means that the browser will send it to ALL virtual directories hosted in the same IIS site. One way to solve this is to adjust the cookie created by ASP.Net to set the path to the virtual directory for the particular app. Then the browser will not send it to other virtual directories. Here is the code to add to global.asax.cs Session_Start:

HttpCookie oCookie = Response.Cookies["ASP.NET_SessionId"];
if (null != oCookie)
{
oCookie.Path = Request.ApplicationPath.ToLower();
}

Let me know if that fixes your problem. If it does not, please email at robertb@aspalliance.com so we can debug more directly.
Title: Always redirects when IsNewSession == true   
Name: Rick Cohen
Date: 2005-01-24 5:51:20 PM
Comment:
What I'm seeing is that even when it's a new session, ASP.NET_SessionId cookie already exists and has a value before it gets checked using this code. So the page always redirects when IsNewSession is true, including the first time in, because the cookie is already set. I placed the code exactly as shown in the example. Any ideas? Thanks.
Title: Greate article   
Name: Mita
Date: 2005-01-11 3:18:53 AM
Comment:
Its very useful..Thanks
Title: Re: Re: Object reference not set to an instance of an object   
Name: Chris N
Date: 2005-01-05 9:34:33 AM
Comment:
Short circuit boolean evaluation can be achieved in VB.NET using the AndAlso or OrElse logical operators. The if-statement in question would be:

If Not IsNothing(strCookieHeader) AndAlso strCookieHeader.IndexOf("ASP.NET_SessionId") >
= 0 Then
Title: Re: Object reference not set to an instance of an object   
Name: Robert Boedigheimer
Date: 2005-01-05 8:33:36 AM
Comment:
One reason why the cookie header may not be present would be if the user disabled cookies in their browser. The problem is that VB.Net does not support "short circuit boolean evaluation" which just means that even if your first expression is false with an AND, it still evaluates the second expression. The code provided in C# would see that the header was null (false) and not attempt to evaluate the second expression. Just change the AND to a nested if with the first level checking if the strCookieHeader is null, if not then do the next if inside of that. Email me at robertb@aspalliance.com if you have further questions
Title: Object reference not set to an instance of an object.   
Name: Mauricio Quiros V.
Date: 2004-12-30 12:47:57 PM
Comment:
I got the error "Object reference not set to an instance of an object." when debugging in this part...

szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0

because "szCookieHeader" is nothing..

Any Suggestions of Why I get this situation..

Full VB code...

If Not context.Session Is Nothing Then
If Session.IsNewSession Then
Dim strCookieHeader As String
strCookieHeader = Request.Headers("Cookie")
If Not IsNothing(strCookieHeader) And strCookieHeader.IndexOf("ASP.NET_SessionId") >= 0 Then
Response.Redirect("ms_sessiontimeout.aspx")
End If
End If
End If
Title: COOL   
Name: RENJESTAA
Date: 2004-12-17 2:49:49 AM
Comment:
NICE STUFF!! I WAS SEARHING FOR THE EXACT TOPIC!! THANX TO WHO EVER IT MAY CONCERN
Title: Re: Kim Bach Petersen   
Name: Robert Boedigheimer
Date: 2004-11-30 8:25:32 AM
Comment:
The solution as presented does not assume the use of Forms Authentication (it was originally created for our intranet sites that use Windows Authentication).
Title: A suggestion   
Name: Kim Bach Petersen
Date: 2004-11-29 4:47:51 PM
Comment:
I suggest checking for

Request.Headers("Cookie").IndexOf(FormsAuthentication.FormsCookieName)

instead of

Request.Headers("Cookie").IndexOf("ASP.NET_SessionId
")

for two reasons:

1/ session-id can be recycled by browsers and simply redirecting because the cookie exist seems to cause an annoying extra request in some scenarios
2/ on sites (web-domains) running more than one web-application an session-id-cookie cannot be used to determine if a user is or has been logged in in a valid way

In other words: checking the forms-authentication-ticket-cookie is a better choice.
Title: Re: Spyros   
Name: Robert Boedigheimer
Date: 2004-11-12 5:19:33 PM
Comment:
I have not tested it with either a web garden or web farm, but I can't see why they would not work. The only infrastructure that would be problematic would be those that use a local state service or in process session and don't properly handle the server affinity (which would be a problem for use of the sessions in general and not just this solution).
Title: Software Developer   
Name: Spyros
Date: 2004-11-12 4:20:58 PM
Comment:
I have a question: Does that logic apply to any type of .NET web application irrespectively of the infrastructure? Can I use the same approach if my application is on a Web Garden or on a Web Farm?

Thank you
Title: Mr   
Name: Michael Renkema
Date: 2004-11-11 7:57:49 PM
Comment:
Thanks for that...
Title: Re: And less code   
Name: Robert Boedigheimer
Date: 2004-11-04 8:12:30 AM
Comment:
I assume you are referring to the code submitted by asp.devnull, and trying to improve it by dropping the IsNewSession in the Session_Start, I did some testing and it seems that IsNewSession will always be true when you are in Session_Start, so it seems that check can safely be removed.
Title: And Less Code   
Name: Martin Smith
Date: 2004-11-03 11:14:39 AM
Comment:
Surely in the Session_Start event it'll always be Session.IsNewSession won't it?
Title: Saludos   
Name: jose mejia
Date: 2004-10-29 2:10:58 PM
Comment:
Esto es seguro
Title: Bowing to the gods   
Name: T
Date: 2004-10-21 4:01:04 PM
Comment:
That was a nice piece of work!
Title: But....   
Name: Leo Bastin
Date: 2004-10-18 3:30:49 AM
Comment:
But... it seems the Session_OnStart event will be fired only if the EnableSessioNState is true. So we can safely write the same code in the global.asax. So the comment "will go to timeout.htm even if
page does not use the session" is somewhat wrong.
Title: Really Cooool :)   
Name: Leo Bastin
Date: 2004-10-18 1:32:26 AM
Comment:
Its really cool and usefull for cookie based session management. ThanX a lot :)
Title: Re; asp.devnull   
Name: Robert Boedigheimer
Date: 2004-10-14 9:09:54 AM
Comment:
The same concept but differs in not checking if session is required (will go to timeout.htm even if page does not use the session) and location of code. Global.asax would certainly work, we use base pages for other reasons so it was natural place for me. If you don't already use base pages, your suggestion would reduce effort to implement. Your suggestion is also marginally more efficient as well since it only runs the code on a new session start rather than each request. Thanks for the feedback!
Title: less work with the same code, place it in the global.asa   
Name: asp.devnull
Date: 2004-10-14 8:36:53 AM
Comment:
Sub Session_Start(...)

If Session.IsNewSession Then

If Not IsNothing(Request.Headers("Cookie")) And Request.Headers("Cookie").IndexOf("ASP.NET_SessionId") >= 0 Then
Response.redirect("timeout.htm")
End If

End If

End Sub
Title: Re: Alternate way to do it   
Name: Robert Boedigheimer
Date: 2004-10-13 8:16:37 AM
Comment:
From previous comment from Dave, I am not sure what you are proposing. If you don't set the Session["foo"] = "X" in Session_Start or somewhere before your first check, then your first request would look like it was a timeout. If you do place the code is Session_Start, then when the session is dropped, a new Session_Start is fired and the value is reset. The session has been lost, but the technique you specified did not determine that. Can you explain it in more detail or email me at robertb@aspalliance.com?
Title: alternate way to do it   
Name: Dave Brasington
Date: 2004-10-12 6:53:40 PM
Comment:
this trick works regardless.
when session established:
Session["Foo"]="X"
later:
if(Session["Foo"]==null) {
Response.Redirect("sessionTimeout.htm");
}
That also works when session gets fried for some other reason.
Title: Cookieless Approach   
Name: Robert Boedigheimer
Date: 2004-10-08 12:53:22 PM
Comment:
I have not tried to implement this for cookieless sessions. Instead of using the section of code for the cookie from the header, it would need to look at the URL for the embedded session id. Assuming the session id is a fixed size, it should be possible to use a regular expression match to look for the (...) session id indicator. If the IsNewSession is true but the session id is present it MIGHT be a timeout. The problem with cookieless is that the user can create a favorite to a page which would include the session id, so even on a new browser session that id would appear and appear to be a lost session.
Title: useful for cookie sessions   
Name: Dan Bachmann
Date: 2004-10-07 5:16:00 AM
Comment:
This is a great article for users for ASP.NET cookie sessions.

Is there a way to do this with ASP.NET cookieless(=true) session management?
Title: nice   
Name: kyubo
Date: 2004-10-03 9:33:49 PM
Comment:
very helpful! thanks!






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-19 1:45:06 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search