How to manage the ASP.NET web service output caching in C#

Web services which use output caching provide identical response, until the cache information expires, when requests are identical. In this case you can increase performance of your site, even if you store a response only for w few seconds.

You should use output caching only for straightforward information retrieval or data-processing functions. You should not use it in a method that performs other work as changing session items, logging usage, or modifying database.  You can enable caching for a method by using the CacheDuration property of the WebMethod attribute:

[System.Web.Services.WebMethod(CacheDuration=50)]

public DataSet GetBooks()

{ … }

 

This example caches the books DataSet for 60 seconds.

You can use output cashing with methods that require parameters:

[System.Web.Services.WebMethod(CacheDuration=50)]

public DataSet GetBooks(string author)

{ … }

In this case, ASP.NET reuses only those requests that supply the same author value. For example, here’s how three web service requests might unfold:

1. A client calls GetBooksByAutor() with the author parameter of  E. L. James. The web method calls, contacts the database, and stores the result in the web service cache.

2. A client calls GetBooksByAuthor() with the author parameter of Suzanne Collins. The web method calls, contacts the database, and stores the result in the web service cache. The previously cached DataSet is not reused, because the author parameter differs.

3. A client calls GetBooksByAuthor() with the author parameter of E.L. James. Assuming ten minutes haven’t elapsed since the request in step 1, ASP.NET automatically reuses the first cached result. No code is executed.

Whether it makes sense to cache this version of GetBooksByAuthor() really depends on how much traffic your web service receives and how many different cities exist.