Evaluate Weigh the pros and cons of technologies, products and projects you are considering.

Stateful Web services in .NET

I have the following:

// ss is the object of the Web service class to which this application refers to.

1) ss.getcatalog(); // returns a value there in that Web service class
2) ss.change(132); // sets the same value
3) ss.getcatalog();

My question is that I cannot update the value in the above way at the Web service class. Does that mean the Web service is stateless? If so, how can I write stateful Web services in .NET?
Web services invoked over HTTP protocol are stateless by design. When the request reaches the Web server, the ASP.NET runtime manages the request by instantiating an instance of your Web service type, deserializing the SOAP envelope XML stream, and invoking the requested method passing parameters if applicable. A new instance of the Web service type is created for each HTTP request targeting the service, so any information stored in data fields contained within the type are recreated for each round trip. If you want to persist state you must specifically enable state for the method as shown here:
[ WebMethod(EnableSession=true) ]
public object getcatalog()
return Session["catalog"];

[ WebMethod(EnableSession=true) ]
public void change(object val)
Session["catalog"] = val;
This will cause the ASP.NET runtime to create an HttpSessionState object the first time a method that has session state enabled is called. Each subsequent call to a method that has session enabled will share the same session state object, so long as the client passes a session cookie with each subsequent request. If the client does not pass a session cookie ASP.NET will create a new session for each call.

The client invoking the service must be session aware, something we take for granted when we navigate Web sites with a browser. The client proxy created for a .NET Web service includes a CookieContainer property, and .NET provides us with CookieContainer type that we can instantiate and assign the proxy as follows:

// create cookie container once for the duration of the session
System.Net.CookieContainer cookies = new System.Net.CookieContainer();

// each time invoking the service, assign the same cookie container before invoking methods
localhost.SessionService1 svc = new localhost.SessionService1();
svc.CookieContainer = cookies;

When the proxy invokes the service, it serializes the method call into a SOAP envelope, and builds an HTTP request with appropriate headers, and posts to the endpoint URI of the Web service. The HTTP headers will include the session cookie if one is provided here, and that's how ASP.NET can find the right session state object to make it available to your Web method.

See the following code sample for a complete example:

Dig Deeper on Topics Archive