views:

440

answers:

2

Hello,

I want to be able to get the SessionID of the currently authenticated session in a WebMethod function where EnableSession = false.

I cannot set EnableSession=true on this request, because another (long running) request on a different page is keeping the SessionState locked (EnableSessionState == "True" not "Readonly").

Is there a consistent way of getting the SessionID from either the ASP.NET Session cookie or the Url for cookieless sessions? I can code it myself but I would rather use a function that is already documented and tested.

Thank you very much,
Florin.

A: 

HttpContext.Current.Session.SessionID

Jeremy Stein
Session is not available on this request, so HttpContext.Current.Session == null.
Florin Sabau
+1  A: 

There seems to be no ASP.NET function that can do this, so I made up a hack of my own, which works... for now ;):

private string GetSessionID(HttpContext context)
{
  var cookieless = context.Request.Params["HTTP_ASPFILTERSESSIONID"];
  if (!string.IsNullOrEmpty(cookieless))
  {
    int start = cookieless.LastIndexOf("(");
    int finish = cookieless.IndexOf(")");
    if (start != -1 && finish != -1)
      return cookieless.Substring(start + 1, finish - start - 1);
  }
  var cookie = context.Request.Cookies["ASP.NET_SessionId"];
  if (cookie != null)
    return cookie.Value;
  return null;
}
Florin Sabau