Detecting ASP.NET Session Timeouts
page 1 of 2
Published: 27 Sep 2004
Abstract
Determine if a user's Session is still active.
by Robert Boedigheimer
Feedback
Average Rating: 
Views (Total / Last 10 Days): 369743/ 2118

Background and How Sessions Are Implemented

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).

It is often useful in an ASP.NET site to know for a particular request if the user’s session information is still intact (that a timeout has not occurred). One common need is to be able to inform the user why they lost their session information, by redirecting to a page that describes the timeout amount and how to avoid the problem in the future.  Without this technique it is difficult to know if a session variable is not present whether it was never set properly or the user waited too long between requests.  Many ASP.NET developers just reference session variables without first ensuring they are actually present.  This causes the infamous "Object reference not set" exception, which can be very difficult to trace back to the specific cause.  Code that checks for null session values is useful, but does not help the developer understand if it was never set properly or if the user just lost her session.  This technique can help to clearly identify that the user waited to long between requests and the session storage information was removed.

This is not the same as using the Session_OnEnd event which can be used for cleanup, logging, or other purposes.  It is also not for enforcing security on a web site. 

How Sessions Are Implemented

Since the HTTP protocol used by web browsers to request files from web servers is stateless, ASP.NET needs to determine which requests were from the same user. The primary mechanism utilizes a non-persistent cookie that is issued by the web server that contains a session id value. The id provided by this cookie is the key used to index into the session infrastructure to access the user's specific data. The session framework is implemented by the HTTP module System.Web.SessionState.SessionStateModule, which executes before the .aspx page events. The module uses the EnableSessionState attribute from the @Page directive to determine if it must retrieve the user’s session information (and whether it needs to write out changes when the request is complete). If the EnableSessionState attribute is true (which it is by default), the module retrieves all of the user’s session information and sets the Session property of the Page class to an instance of the HttpSessionState class. This article focuses on the cookie mechanism, although a cookie-less method of sessions is implemented in ASP.NET (the session id is embedded in the URL string). The Session information can be stored in-process (default, stores in web server memory), with a state service, or a SQL Server database. This article will focus on the in-process storage, but the technique applies to all three locations.

Example User Session

A user opens a browser instance and requests an ASP.NET page from a site. If the EnableSessionState attribute is true, the session module adds the ASP.NET_SessionId cookie to the response. On subsequent requests to the same web site, the browser supplies the ASP.NET_SessionId cookie which the server side module uses to access the proper user’s information.


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 6 and 7 and type the answer here:

User Comments

Title: Re: Dracked   
Name: Robert Boedigheimer
Date: 12/22/2008 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: 12/17/2008 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: 12/12/2008 7:31:19 AM
Comment:
This solves the mystry of sessions
Title: nice article   
Name: ramulu
Date: 11/26/2008 4:10:56 AM
Comment:
It was very nice article. We Handled in Our Project.
Title: Re: R.Brahma chary   
Name: Robert Boedigheimer
Date: 9/30/2008 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: 9/29/2008 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: 9/29/2008 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: 9/27/2008 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: 9/22/2008 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: 9/22/2008 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: 9/19/2008 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: 9/13/2008 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: 8/23/2008 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: 7/31/2008 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: 7/15/2008 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: 7/11/2008 2:10:38 AM
Comment:
thanx

www.codepal.co.in
Title: Re: Maha   
Name: Robert Boedigheimer
Date: 7/10/2008 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: 7/9/2008 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: 7/9/2008 10:25:43 AM
Comment:
Can i use basePageSessionExpire in Master page
Title: ASP.NET   
Name: Ragunathan.M., MCA
Date: 7/9/2008 7:18:47 AM
Comment:
Good..
Title: log out code   
Name: prajeesh
Date: 7/4/2008 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: 5/15/2008 7:46:28 AM
Comment:
Fine
Title: asp.net   
Name: vasu
Date: 5/7/2008 1:41:00 AM
Comment:
i cont understand u r coding plz give properly information
Title: ASP.NET   
Name: ROHIT CHATURVEDI
Date: 5/5/2008 8:50:38 AM
Comment:
this is not the propr way
Title: R.Sathish Kumar.,MCA   
Name: AnnaNagar-Chennai
Date: 4/29/2008 2:44:09 AM
Comment:
Good..
Title: Re: S.MaheshKumar   
Name: Robert Boedigheimer
Date: 4/21/2008 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: 4/19/2008 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: 4/16/2008 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: 4/16/2008 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: 4/9/2008 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: 4/9/2008 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: 4/9/2008 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: 4/7/2008 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: 4/7/2008 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: 3/17/2008 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: 3/5/2008 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: 3/5/2008 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: 2/22/2008 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: 2/22/2008 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: 2/13/2008 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: 2/13/2008 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: 2/12/2008 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: 2/7/2008 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: 1/26/2008 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: 1/16/2008 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: 1/15/2008 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: 1/15/2008 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: 1/4/2008 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: 1/3/2008 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: 12/31/2007 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: 12/19/2007 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: 11/30/2007 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: 11/7/2007 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: 11/7/2007 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: 10/22/2007 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: 10/19/2007 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: 10/12/2007 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: 10/11/2007 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: 10/11/2007 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: 10/11/2007 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: 10/9/2007 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: 10/8/2007 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: 10/8/2007 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: 10/5/2007 3:47:45 AM
Comment:
simple example coding in ASP.Net session.
Title: Re: Greg R   
Name: Robert Boedigheimer
Date: 10/3/2007 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: 10/3/2007 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: 10/2/2007 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: 9/28/2007 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: 9/10/2007 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: 8/27/2007 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: 8/24/2007 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: 8/10/2007 2:46:25 AM
Comment:
good guidance for the davalopers
Title: Define Session period for Loss session   
Name: Rajesh Bhatiya
Date: 8/3/2007 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: 8/1/2007 5:25:38 AM
Comment:
thanks.
Title: Re: B.V.Rajaram   
Name: Robert Boedigheimer
Date: 7/27/2007 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: 7/27/2007 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: 7/10/2007 11:27:52 AM
Comment:
\
Title: More than one dotnet app per server   
Name: Mike H
Date: 7/5/2007 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: 7/3/2007 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: 6/29/2007 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: 6/27/2007 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: 6/25/2007 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: 6/13/2007 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: 6/12/2007 11:03:13 AM
Comment:
how can we see session information in server
Title: Re: Sippy   
Name: Robert Boedigheimer
Date: 6/12/2007 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: 6/8/2007 5:53:53 AM
Comment:
what u mean by cookieless.
Title: Virtual Directories and Applications   
Name: Robert Boedigheimer
Date: 5/18/2007 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: 5/9/2007 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: 4/19/2007 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: 4/19/2007 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: 4/18/2007 2:55:19 AM
Comment:
How to implement this if i use cookieless mode for session state?
Title: Re: Divya   
Name: Robert Boedigheimer
Date: 4/9/2007 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: 4/9/2007 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: 3/29/2007 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: 3/26/2007 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: 2/26/2007 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: 2/23/2007 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: 2/20/2007 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: 2/16/2007 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: 2/16/2007 5:25:55 AM
Comment:
It is very Good article. So helpful
Title: Too good   
Name: amrita
Date: 2/9/2007 8:43:21 AM
Comment:
very help ful, concise but informative.
Title: super   
Name: saravanan
Date: 2/6/2007 2:48:14 PM
Comment:
this is a super article fro session
Title: Re: Vasanth   
Name: Robert Boedigheimer
Date: 1/23/2007 8:27:56 PM
Comment:
No, ASP and ASP.NET do not share sessions
Title: Sessions On ASP and ASP.Net   
Name: Vasanth
Date: 1/11/2007 7:54:19 AM
Comment:
Can use Session Created in .asp file same in .aspx file
Title: Re: Joe Beam   
Name: Robert Boedigheimer
Date: 1/4/2007 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: 1/4/2007 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: 1/4/2007 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: Hola   
Name: ureyes84
Date: 12/29/2006 11:21:19 AM
Comment:
Nice......

Gracias for sharing
Title: Session expires in first access....   
Name: Rodrigo - rodrigoszn@gmail.com
Date: 12/14/2006 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: nice   
Name: sambath
Date: 12/5/2006 5:05:56 AM
Comment:
good article...
Title: Re: Sompop   
Name: Robert Boedigheimer
Date: 11/29/2006 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: 11/28/2006 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: 11/27/2006 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: 11/27/2006 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: 11/27/2006 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: 11/27/2006 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: 11/21/2006 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: 11/15/2006 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: 11/15/2006 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: 10/19/2006 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: 10/19/2006 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: 10/12/2006 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: 10/12/2006 3:52:49 AM
Comment:
very nice,what is sessionTimeout.htm
Title: Re: Rod   
Name: Robert Boedigheimer
Date: 9/25/2006 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: 9/22/2006 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: 9/12/2006 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: 8/27/2006 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