Get SessionID via WebMethod from VB.NET to JavaScript

481 Views Asked by At

I'm a little clueless having the following code just not working:

Code-behind:

<WebMethod(EnableSession:=True)>
Public Shared Function GetSessionID() As String
    Dim sID = HttpContext.Current.Session.SessionID
    Debug.WriteLine(sID)
    Return sID
End Function

JavaScript:

var sID;

function init() {
    sID = PageMethods.GetSessionID();
...

The sID is obviously there and shown in debug output but in JavaScript sID holds "undefined" because the function returns "undefined" when executed in Firebug console. What's going on there?

2

There are 2 best solutions below

2
krlzlx On BEST ANSWER

You need to define the OnSuccess callback of your PageMethods like this:

var sID;

function init() {
    PageMethods.GetSessionID(OnSuccess);
}

function OnSuccess(response, userContext, methodName) {
    sID = response;
    alert(sID);
}

References:

1
DreamTeK On

Your code looks OK. Where are you calling the function from? Try defining the variable inside the function:

function init() {
    var sID = PageMethods.GetSessionID();
}

If you are trying to read the sessionID why not just read directly from the cookie?

JavaScript

function readCookie(name) {
  var nameEQ = escape(name) + '=',
    ca = document.cookie.split(';'),
    i = 0,
    c;
  for (i = 0; i < ca.length; i++) {
    c = ca[i];
    while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
    if (c.indexOf(nameEQ) === 0) { return unescape(c.substring(nameEQ.length, c.length)); }
  }
  return null;
}

var sID = readCookie('ASP.NET_SessionId');