about me

How to: Manage State in Web Services Created Using ASP.NET

| 23 thg 11, 2009
Web services have access to the same state management options as other 
ASP.NET applications when the class that implements the Web service derives from 
the WebService class. The 
WebService class contains many of the common ASP.NET objects, including 
the Session and 
Application 
objects.

using System.Web.Services;

public class ServerUsage : WebService {
   [ WebMethod(Description="Number of times this service has been accessed.") ]
   public int ServiceUsage() {
     // If the 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 particular client session has accessed this Web service method.",EnableSession=true) ]
   public int PerSessionServiceUsage() {
     // If the 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"];
   }
}

0 nhận xét:

Đăng nhận xét