12.2 Use Response Caching in an XML Web Service


Problem

You want to improve XML Web service performance by caching the return value of a Web method.

Solution

Use response caching by setting the CacheDuration property of the System.Web.Services.WebMethod attribute.

Discussion

In ASP.NET, XML Web services support response caching in much the same way as ASP.NET Web pages. When response caching is enabled, your code runs only once, and the return value of the Web method is stored and returned on subsequent method invocations. With Web forms, caching is performed on a per-form basis. With XML Web services, caching is enabled and configured distinctly for each Web method.

For example, the following Web method returns the current date and time on the server. This information is cached for one minute, meaning that subsequent requests within this timeframe will receive the previously recorded date information.

 using System; using System.Web.Services; public class ResponseCaching {     [WebMethod(CacheDuration=60)]     public string GetDate() {         return DateTime.Now.ToString();     } } 

If your Web method accepts parameters, ASP.NET will reuse the cached method result only if it receives a request with the same parameter values. If you have a method that accepts a wide range of values, caching might be ineffective or even wasteful because a great deal of information might be stored in the cache but rarely reused. For example, a Web method that performs a mathematical calculation based on numeric input is rarely a good choice for response caching. On the other hand, a Web method that accepts an ID referencing one of a dozen different product items probably is. As always, response caching bypasses your code, making it unsuitable if your Web method needs to perform other actions (such as logging activity) or if your Web method depends on information that's not supplied through method parameters (such as user authentication information or session data).

Note  

One limitation of response caching with Web methods is that it allows you to reuse data only within the bounds of a single method. If you want to reuse specific data in different Web methods , data caching (described in the following recipe) will be more effective.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net