Using Session with ASP.NET Web Services and Generic Handlers

Posted on November 19, 2010 by Frederik Vig in ASP.NET

After refactoring some code today, going from cookies to using ASP.NET session instead, I noticed some problems with the Web Services and Generic Handlers (this application used a lot of JavaScript and Ajax). The problem was that the Session collection was always null. After checking out the documentation on MSDN I came across the solution (turned out be quite simple).

Web Services

In the WebMethod attribute you need to set the property EnableSession to true (told you it was simple).

using System.ServiceModel;
using System.Web.Script.Services;
using System.Web.Services;
 
namespace Coop.Web.Templates.WebServices.MegaStore
{
    [WebService(Namespace = "http://schema.company.com")]
    [XmlSerializerFormat]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Manager : WebService
    {
        [WebMethod(EnableSession = true)]
        public string MyMethod()
        {
            // you can now use the session collection: Session
        }
    }
}

Generic Handlers

For Generic Handlers you need to implement the interface IReadOnlySessionState, located in System.Web.SessionState.

using System.Web;
using System.Web.SessionState;
 
namespace Playground
{
    public class MyGenericHandler: IHttpHandler, IReadOnlySessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            // you can now use the session collection: context.Session
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Related Posts: