How to use Sessions in Web Services ASP.Net

11 Apr

Using sessions in web services is little different from its normal usage. Here we can not access sessions with Session as in Page methods. Instead we use HttpContext.Current.Session.

Sessions should be enabled for web methods.

A sample code snippet would be as follows.

/// Summary description for ReceivingService
    /// </summary>
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    public class ReceivingService : System.Web.Services.WebService

        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public Dictionary<string, object> removeItem(int Id)
            var response = new Dictionary<string, object>();
            bool found = false;

            if ( HttpContext.Current.Session["rec_cart"] != null)
                List<CartItem> cartItems = (List<CartItem>)Session["rec_cart"];
                if (cartItems.Count > 0)
                    foreach(var item in cartItems){
                        if(item.Id == Id){
                             HttpContext.Current.Session["rec_cart"] = cartItems;
                            found = true;
            if (found)
                response["status"] = true;
                response["total"] = GetGrandTotal();
                response["status"] = false;
            return response;

I also configured cookieless sessions in web.config to get web service call properly routed.

<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="100"/>
Leave a comment

Posted by on April 11, 2015 in ASP.Net



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: