Getting session in .NET ASMX web-service

Matt picture Matt · Jul 21, 2010 · Viewed 32.8k times · Source

I have an ASMX webservice hosted alongside my ASP.NET web app. Now, I need to get the users session into the Webservice. To test this I made this simple method:

    [WebMethod(EnableSession = true)]
    public string checkSession()
    {
        return HttpContext.Current.Session["userid"].ToString();
    }

So, first I login to my web app, then in the browser goto my webservice and click "checkSession" on that auto generated test page. I have tested this on 3 computers. All 3 of those work fine with the webapp(so the sessions are being created etc), and 2 of those return the value of Session["userid"] on invoking the webmethod, however the last computer returns "Object reference not set to an instance of an object" because Session is null.

So, whats the difference between these computers and why can my ASP.NET app get the sessions on all computers but the webservice cant?

Answer

Pietro Allievi picture Pietro Allievi · Jun 1, 2017

maybe it's too late, but have you tried this:

[WebMethod(EnableSession = true)]
public string checkSession()
{
    return HttpContext.Current.Session.SessionID
}