Home   Cover Cover Cover Cover
 

State Management and Life Cycle


From Section 7.4.4 of the book

If a web service is invoked the IIS creates an object that processes the request. Invocations of different web service methods can share state information using the session state (Session) and the application state (Application).

This example simple increments two request counters, one for the whole application and one for every session (see method IncSession). The application state is shared by all sessions and is retains its value until the application (i.e. the ASP.NET runtime) is restarted.

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

[WebService(Namespace="http://dotnet.jku.at/StateDemo/")]
public class StateDemo : WebService {
  [WebMethod()]
  public int IncApplication() {
    int hit = (Application["Hit"] == null) ? 0 : (int) Application["Hit"];
    hit++;
    Application["Hit"] = hit;
    return hit;
  }

  [WebMethod(EnableSession=true)]
  public int IncSession() {
    int hit = (Session["Hit"] == null) ? 0 : (int) Session["Hit"];
    hit++;
    Session["Hit"] = hit;
    return hit;
  }
}

If you copy this code to a file StateDemo.asmx in a virtual directory of your local machine you can open it with Internet Explorer and get a test page that allows you to invoke the methods IncApplication and IncSession. In order to increment different session counters you should open two instances of the Internet Explorer and call IncSession from both of them.

Alternatively, you can test your web service also with WebService Studio.