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.
[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.
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 the application state.