Implementing Session in WebService

As we all know that all web applications are stateless and webServices are no exceptions.There are various techniques of state management in web applications viz
Hidden Fields
Since web services don't have any user interface we can't use Hidden fields and ViewState for maintaining state. Here in we will discuss how to maintain session in web services.
In my previous post regarding web services attributes I have specified what all attributes a web service can have and what is the use of each attribute. Let's talk in depth about EnableSession attribute:-

The EnableSession property is a Boolean property and allows us to enable sessions (this requires the use of the proxy object, which will be discussed in another article). Without the proxy object, this web property cannot be implemented as the property is discarded as soon as the value is assigned to it. Without a proxy object, only one request is allowed per session, and assigning a value to the property itself is a request and therefore the session is ended just after.
Now just have a look at the below code
public void SetSessionVariable(string str)
Session["id"] = str;

public string GetSessionVariable()
if ( Session["id"] != null )
return Session["id"].ToString();
return "Nothing in Session";
When you run this code for the first time It will give Object reference error in SetSessionVariable function since Session is not enables and thus Session object will be null.
To get around this issue you just need to tweak the WebMethod attribute a bit.Append the WebMethod attributes to the functions to enable sessions.

public void SetSessionVariable(string str)
Session["id"] = str;

public string GetSessionVariable()
if ( Session["id"] != null )
return Session["id"].ToString();
return "Nothing in Session";
Now try to run this sample by writing the following code
localhost.Service obj = new localhost.Service();
obj.SetSessionVariable(“Some Value");
MessageBox.Show(obj. GetSessionVariable().ToString());
What Happened this time?Did we get the value this time round from session?What have we done wrong……………
Well the web service code is ok but since web Services are stateless where will they store the session information. System.Net.CookieContainer class comes to the rescue.Since web services are a complete framework you will find a lot of things when you have just created them by writing a simple function one og the things is a CookieContainer property.Yeah you have to set this property to get the session thing working for you.
So here goes the complete code

localhost.Service obj = new localhost.Service();
System.Net.CookieContainer container= new System.Net.CookieContainer();
obj.SetSessionVariable(“Some Value");//Sets value in session
MessageBox.Show(obj. GetSessionVariable().ToString());//Retrieves value from Session


Author: Rahul Sharma28 May 2008 Member Level: Silver   Points : 2

Excellent article! Thanks a lot, I tried this and my application is able to mantain sessions on webservice. Please do let me know about the web service security with examples. It would be great help for me as this.

Author: vijayavasavi narapuram29 May 2008 Member Level: Silver   Points : 2

Very nice article..Thanks for posting this article in dotnet spider...

Author: Kumar Velu30 May 2008 Member Level: Gold   Points : 2

Excellent article!

Author: Sarfraz Ahmad30 May 2008 Member Level: Silver   Points : 2

Nice article !

Author: ramesh.v30 May 2008 Member Level: Bronze   Points : 2

hi this is very nice article

Author: suhati gupta30 May 2008 Member Level: Silver   Points : 2

very important and good article.Thanks

Author: kannammal29 Dec 2009 Member Level: Bronze   Points : 0


Author: Sharad Sharma29 Mar 2010 Member Level: Gold   Points : 0

Its a good article... Please keep on sending such articles.


Author: Durga Prasad30 Mar 2010 Member Level: Gold   Points : 0

Thank You for sharing

Author: Mallikarjuna30 Mar 2010 Member Level: Gold   Points : 0

very Nice Article....... keep on posting


Author: T.C.P.Elavarasu18 Nov 2010 Member Level: Silver   Points : 1

Hi shakti Singh,
I appreciate your good work. At the same time this article will be complete only when you explain about maintaining session in Webservice WITHOUT COOKIES

Author: vishnu20 Nov 2010 Member Level: Bronze   Points : 0

Thanks so much for this article.


Author: Naveen Chauhan07 Jan 2011 Member Level: Gold   Points : 0

Great work man.....keep it up

Author: Ravindran07 Jan 2011 Member Level: Gold   Points : 0

Excellent Aritical

easily udnerstand session in webservice

Good work

Author: Siva Prasad07 Jul 2012 Member Level: Gold   Points : 1

In this line I got error as CookieContainer is not a property of proxyObject:
proxyObj.CookieContainer = containerObj;

Then I generated property in references.cs as below. Then error gone. Is it correct?

public System.Net.CookieContainer CookieContainer { get; set; }

Author: Siva Prasad07 Jul 2012 Member Level: Gold   Points : 0

I have implemented your code, Every time "Nothing in Session" kind of alert message box coming to me. What might be the reason. Can you tell me? Shall I send my code here?

Author: rajesh kumar parbat20 Jul 2012 Member Level: Gold   Points : 0

Nice One Article

Author: Sumit Pyne28 Aug 2012 Member Level: Silver   Points : 0

Thanks for sharing very informative article.
But One doubt, I have provided the following code in an asmx file.

[WebMethod(EnableSession = true)]
public void setData(string mode)
ABC obj;
obj = (ABC)System.Web.HttpContext.Current.Session
obj.Type = mode;

I called this service from Javascript which in turns call the webmethod of this asmx service and set the session object with the value provided as input. We found the session object("MODE") with updated vale, is available in the web server.

But I don't need any System.Net.CookieContainer object, please provide me some thoughts.


Author: ketan Italiya23 Aug 2013 Member Level: Gold   Points : 3

Usually, when you think of a Web Service, you think …make the call, get the response, and get on with the task at hand. These "one shot" calls are the norm in Web Services but there may be times when you need a little more. You may need the Web Service to remember states between calls.

As an example, I wrote a Web Service that had to perform a lengthy operation. I didn't want to lock up the client by making a synchronous call, so once the job was started, the call returned. Every few seconds, on a timer, the client would call a GetStatus function in the Web Service to get the status of the running job. When the status was retrieved, a progress bar on the client was updated. It worked well.

Author: ketan Italiya23 Aug 2013 Member Level: Gold   Points : 4


One of the most common challenges that Web developers encounter is maintaining state in the stateless world of HTTP. There have been a number of clever means used to get around the stateless issue, from reposing application data with each request, to using HTTP authentication to map requests to specific users, to using HTTP cookies to preserve the state of a series of requests. One particularly clever way of maintaining state that hides all the challenging work below is to simply use the Microsoft® ASP.NET System.Web.SessionState.HttpSessionState class. You can use the ASP.NET HttpSessionState class from a Web method just as you can from ASPX pages, but things work a little differently for Web methods.
Quick Overview of ASP.NET Sessions

ASP.NET session state is maintained by using one of two underlying mechanisms. The first is by using HTTP cookies. The idea behind HTTP cookies is that when the client sends a request, the server sends back a response with an HTTP Set-Cookie header that has a name/value pair in it. For all subsequent requests to the same server, the client sends the name/value pair in an HTTP Cookie header. The server then can use the value to associate the subsequent requests with the initial request. ASP.NET uses a cookie that holds a session ID to maintain session state. Then that ID is used to find the corresponding instance of the HttpSessionState class for that particular user. The HttpSessionState class provides just a generic collection in which you can store any data that you want.

The other mechanism that ASP.NET uses for maintaining session state works without cookies. Some browsers do not support cookies or are not configured to keep and send cookies. ASP.NET provides a mechanism for getting around this problem by redirecting a request to a URL that has the ASP.NET session ID embedded in it. When a request is received, the embedded session ID is simply stripped out of the URL and is used to find the appropriate instance of the session object. This works great for browsers that are doing HTTP GET requests, but creates issues when writing Microsoft® .NET code that consumes an XML Web service.

It should be noted that sometimes it makes sense to store state information in cookies themselves instead of in the ASP.NET session object. By avoiding the session object, you use fewer resources on the server, and you do not have to worry about issues like locating a specific instance of the session object across a Web farm, instances of the session object being cleaned up because of a long delays between requests, or session instances lingering around for no reason until their timeout period expires. However, if you have data that includes implementation information that you do not want to share with the consumers of your service, or is private data that you do not want to send across an unencrypted channel, or if the data would be impractical to serialize into an HTTP header, then it may make sense to take advantage of the HttpSessionState class in ASP.NET. The HttpSessionState class returns an index key that is used to map a particular user to an instance of the HttpSessionState class that holds information stored for that user. Both the ASP.NET HttpSessionState class and HTTP cookies are available to users writing ASP.NET Web services.
Why Use an HTTP Mechanism for Maintaining State in an XML Web Service?

There are many ways to maintain state between SOAP requests. Certainly one feasible option would be to include something like the ASP session ID in the SOAP header of your SOAP message. The problem is that you have to: 1) still write the server side code yourself, and 2) make sure your clients treat your session ID header like an HTTP cookie and send it back to you with each request. There are certainly cases where using the SOAP header approach makes a lot of sense, but there are situations where using the HTTP approach can make sense as well.

ASP.NET session state is already done for you. The HttpSessionState class is available for easily storing your session objects. Most HTTP clients already understand that they must return the cookies that are set by the server and HttpSessionState happens to support the underlying transport most frequently used for SOAP communications—HTTP. Thus it makes sense that using ASP.NET session support could be a smart decision to meet many state management requirements.
Enabling Session Support on the Server

By default, ASP.NET session support for each Web method is turned off. You must explicitly enable session support for each Web method that wants to use session state. This is done by adding the EnableSession property to the WebMethod attribute of your function. The code for a Web method with the EnableSession property set to true, and which accesses the HttpSessionState object

Author: Umesh Bhosale29 May 2014 Member Level: Silver   Points : 0

Nice Article

Umesh Bhosale

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: