Application State via HttpContext

Web services have access to the Application object (as do all ASP.NET resources) via the HttpContext object.

So, for example, you could modify Example 15-4 to add the two web methods shown in Example 15-5, SetStockExchange and GetStockExchange, to set and retrieve a value in application state.

Example 15-5. Adding application state to StockTickerComplete

[WebMethod]
public void SetStockExchange(string Exchange)
{
   Application["exchange"] = Exchange;
}

[WebMethod]
public string GetStockExchange()
{
   return Application["exchange"].ToString();
}

You could accomplish the same thing without inheriting from System.Web.Services.WebService by using the HttpContext object, as shown in Example 15-6.

Example 15-6. Adding application state without inheriting WebService

               
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System;      //  necesary for String class
{
   public class Service
.
.
.
      [WebMethod]
      public void SetStockExchange(string Exchange)
      {
         
         HttpApplicationState app;
         app = HttpContext.Current.Application;
         app["exchange"] = Exchange;
      }

      [WebMethod]
      public string GetStockExchange()
      {
         
         HttpApplicationState app;
         app = HttpContext.Current.Application;
         return app["exchange"].ToString();
      }

In Example 15-6, you must add a reference to System.Web at the top of the listing (VS2005 does this by default.). The web service class, Service, no longer inherits from the class WebService. Finally, an HttpApplicationState object is declared to access ...

Get Programming ASP.NET, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.