views:

321

answers:

3

I'm recording the session start times from when people log into my .NET 2.0 web application, but I'd also like to record the Session ID. Can someone give me some example code on how to accomplish this (how to access the Session ID from within the Global.ASAX).

If you need any additional info just let me know.

+4  A: 

HttpContext.Current.Session.SessionID

Edit to show null test:

if ((HttpContext.Current != null) && (HttpContext.Current.Session != null) {
  id = HttpContext.Current.Session.SessionID
}
Ray
I would advise you to check this for null as well just to be safe.
Nissan Fan
"I would advise you to check this for null as well just to be safe"Whats the best way to do that?
Albert
I added a suggestion to my answer
Ray
When I try to check for Null (!= null), I get "null is not declared. Null constant is no longer supported. Use 'System.DBNull' insteadI'm programming in VB if that matters
Albert
In VB you would use Nothing instead of null. null is the C# keyword.
technophile
Great, thanks for the info
Albert
+1  A: 

You can get at it quite simply with HttpContext.Current.Session.SessionId as you probably already know. You need to be on or after Application_AcquireRequestState before the session state has been loaded, and session state is also only loaded when the requested resource implements IRequiresSessionState. You can see a list of all the events in global.asax here: http://articles.techrepublic.com.com/5100-10878_11-5771721.html and read more about IRequiresSessionState here: http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx

klausbyskov
A: 

Write to the session the datetime and sessionid at the moment of the first request following ASP.NET's identifying the user's session.

protected void Application_PreRequestHandlerExecute(object sender, EventArgs eventArgs) {
    var session = HttpContext.Current.Session;
    if (session != null) {
        if (session["foo"] == null) {
            session["foo"] = DateTime.Now.Ticks + "|" + session.SessionID;
        }
    }
}
lance