Managing State in Web Services

A web service is really nothing more than a specialized type of ASP.NET page. As such, a web service is actually part of an ASP.NET web application and can take advantage of application state management techniques such as using the Application object. In addition, session state can be enabled or disabled using properties of the WebMethod attribute.

State should be used sparingly within web services. Maintaining state between multiple calls to the same web service can potentially lead to scalability problems and even inconsistent data. If you absolutely have to make use of some means of state maintenance, then consider using session state over application state, because application state can grow rapidly and has the potential of creating memory problems. Refer to Chapter 23, "State Management in ASP.NET 2.0," for more details on the reasons for and against the various types of state management.

To enable session state and use application state within a web service, you can use code similar to the code in Listing 32.6.

Listing 32.6. State-Aware Web Service

[WebMethod(Description="Sets a session state variable",     EnableSession=true)] public void SetSessionVariable(string variable, string value) {     Session[variable] = value; } [WebMethod(Description="Queries a session state variable",     EnableSession=true)] public string QuerySessionVariable(string variable) {     return (string)Session[variable]; } [WebMethod(Description="Sets an application-wide variable")] public void SetAppVariable(string variable, string value) {     Application[variable] = value; } [WebMethod(Description="Obtains an application-wide variable")] public string GetAppVariable(string variable) {     return (string)Application[variable]; } 

Deciding which state management method you want to use will be a decision very similar to the decision made for a standard ASP.NET application's state management solution. The difference is that web services tend to be invoked more frequently than web pages and typically have different usage patterns. You will generally want to keep state maintenance for web services even lower (if used at all) than what is used for ASP.NET Web Forms applications. This is because each method should be considered a discrete unit of functionality, and subsequent method calls should not normally depend on state created by previous method calls.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: