0

i search google and found many answers for detecting session expiry programmatically. this is code which i saw everyone use it

global.asax
---------------
protected void Session_Start(object src, EventArgs e)
{
if (Context.Session != null && Context.Session.IsNewSession)
{
    string sCookieHeader = Request.Headers["Cookie"];
    if (null != sCookieHeader && sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)
        Response.Redirect("/Session/Timeout");
}
}

i have few question on the above code 1) when session expire then how Context.Session will not be null? 2) what is the meaning of this line Request.Headers["Cookie"];

looking for good discussion. thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626
  • on Session_Start, Session.IsNewSession will always be true. What are you trying to accomplish because I think you're headed down the wrong path. – Lawrence Johnson Oct 05 '12 at 07:16
  • If you want to hook up to session end check out this. http://stackoverflow.com/questions/621744/how-to-handle-session-end-in-global-asax – Yiğit Yener Oct 05 '12 at 07:35

2 Answers2

1

You can use the Session_End method in global.asax file

void Session_End(Object sender, EventArgs E) {
    // Clean up session resources
}
Shai Cohen
  • 6,074
  • 4
  • 31
  • 54
Jack Spektor
  • 1,097
  • 1
  • 11
  • 30
0

1) when session expire then how Context.Session will not be null?

Your code triggers when a user comes back to the server with an expired session. The session object in this code is the new empty session which is beginning. Remember you are in Session_Start, not in Session_End.

2) what is the meaning of this line Request.Headers["Cookie"];

The cookie contains the session's id. If a user is requesting a ressource, providing a session id, and Session_start is triggered, that almost certainly means that the session id refers to an expired session object. A specific message is then displayed to the user.

jbl
  • 15,179
  • 3
  • 34
  • 101