Monday, August 06, 2007

Managing State in XML Web Services Created Using ASP.NET

XML Web services have access to the same state management options as other ASP.NET applications when the class implementing the XML Web service derives from the WebService class. The WebService class contains many of the common ASP.NET objects, including the Session and Application objects.

The Application object provides a mechanism for storing data that is accessible to all code running within the Web application, whereas the Session object allows data to be stored on a per-client session basis. If the client supports cookies, a cookie can identify the client session. Data stored in the Session object is available only when the EnableSession property of the WebMethod attribute is set to true for a class deriving from WebService. A class deriving from WebService automatically has access to the Application object.


To access and store state specific to a particular client session

Declare an XML Web service method, setting the EnableSession property of the WebMethod attribute to true.

[ WebMethod(EnableSession=true) ]
public int PerSessionServiceUsage()

The following code example is an XML Web service with two XML Web service methods: ServerUsage and PerSessionServerUage. ServerUsage is a hit counter for every time the ServerUsage XML Web service method is accessed, regardless of the client communicating with the XML Web service method. For instance, if three clients call the ServerUsage XML Web service method consecutively, the last one receives a return value of 3. PerSessionServiceUsage, however, is a hit counter for a particular client session. If three clients access PerSessionServiceUsage consecutively, each will receive the same result of 1 on the first call.


<%@ WebService Language="C#" Class="ServerUsage" %>
using System.Web.Services;

public class ServerUsage : WebService {
[ WebMethod(Description="Number of times this service has been accessed.") ]
public int ServiceUsage() {
// If the XML Web service method hasn't been accessed,
// initialize it to 1.
if (Application["appMyServiceUsage"] == null)
{
Application["appMyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Application["appMyServiceUsage"] = ((int) Application["appMyServiceUsage"]) + 1;
}
return (int) Application["appMyServiceUsage"];
}

[ WebMethod(Description="Number of times a particualr client session has accessed this XML Web service method.",EnableSession=true) ]
public int PerSessionServiceUsage() {
// If the XML Web service method hasn't been accessed, initialize
// it to 1.
if (Session["MyServiceUsage"] == null)
{
Session["MyServiceUsage"] = 1;
}
else
{
// Increment the usage count.
Session["MyServiceUsage"] = ((int) Session["MyServiceUsage"]) + 1;
}
return (int) Session["MyServiceUsage"];
}
}

No comments: