Saturday, November 15, 2008

Caching in ASP.Net WebService

One of the ways to enhance Web Service Performance is by caching data.

Various caching mechanisms possible are:

·         ASP.NET Output Caching

·         HTTP Response Caching

·         ASP.NET Application Caching

Before using any caching mechanism caching design for a Web service no. issues will be required to be considered and addressed, like:

·         How frequently the cached data needs to be updated

·         Whether the data is user-specific or application-wide

·         What mechanism to use to indicate that the cache needs updating, etc 

Which caching mechanism could be used will depend upon the pros and cons of each method and the properties of the data being returned.

 

ASP.NET Output Caching:

This type of caching could be considered when the data is static or almost static. 

This could be simply achieved by adding a ‘CacheDuration’ property to the WebMethod.

 

e.g.

  [WebMethod ( CacheDuration = 60)]

  public string GetCacheEntryTime(string Name)

    {

        StringBuilder sb = new StringBuilder("Hi ");

        sb.Append(Name);

        sb.Append(", the Cache entry was made at ");

        sb.Append(System.DateTime.Now.ToString());

       

        return (sb.ToString());

    }  

 

The method could be tested by calling it repeatedly with same and different parameters.

Calling the method in following sequence with a gap of 1 min:

textwriter.WriteLine(webService.GetCacheEntryTime("Angelina"));

textwriter.WriteLine(webService.GetCacheEntryTime("Brad"));

textwriter.WriteLine(webService.GetCacheEntryTime("DiffAngelina"));

textwriter.WriteLine(webService.GetCacheEntryTime("DiffBrad"));

textwriter.WriteLine(webService.GetCacheEntryTime("Angelina"));

textwriter.WriteLine(webService.GetCacheEntryTime("Brad"));

 

Results in Output as follows:

Hi Angelina, the Cache entry was made at 12/11/2007 1:16:37 PM

Hi Brad, the Cache entry was made at 12/11/2007 1:16:38 PM

Hi DiffAngelina, the Cache entry was made at 12/11/2007 1:16:41 PM

Hi DiffBrad, the Cache entry was made at 12/11/2007 1:16:42 PM

Hi Angelina, the Cache entry was made at 12/11/2007 1:16:37 PM

Hi Brad, the Cache entry was made at 12/11/2007 1:16:38 PM

 

Notice the same time stamp for same parameter value passed.

The .asmx page of Web Service by Default uses POST with “No-Cache” specified. Thus, this could not be tested with the test page of Web Service.

If the client wants to override server side output caching then it is possible by specifing “No-Cache” while making the request.

No comments: