Monday, January 21, 2013

Caching and the Query String in ASP.NET

One of the main considerations in caching is deciding when a page can be reused and when information must be accurate up to the latest second. Developers, with their love of instant gratification (and lack of patience), generally tend to overemphasize the importance of realtime information. You can usually use caching to efficiently reuse slightly stale data without a problem and with a considerable performance improvement.

Of course, sometimes information needs to be dynamic. One example is if the page uses information from the current user’s session to tailor the user interface. In this case, full page caching just isn’t appropriate, because the same page can’t be reused for requests from different users (although fragment caching may help). Another example is if the page is receiving information from another page through the query string. In this case, the page is too dynamic to cache—or is it?

The current example sets the VaryByParam attribute on the OutputCache directive to None, which effectively tells ASP.NET that you need to store only one copy of the cached page, which is suitable for all scenarios. If the request for this page adds query string arguments to the URL, it makes no difference—ASP.NET will always reuse the same output until it expires. You can test this by adding a query string parameter manually in the browser window. For example, try tacking ?a=b on to the end of your URL. The cached output is still used. Based on this experiment, you might assume that output caching isn’t suitable for pages that use query string arguments. But ASP.NET actually provides another option. You can set the VaryByParam attribute to * to indicate that the page uses the query string and to instruct ASP.NET to cache separate copies of the page for different query string arguments:
<%@ OutputCache Duration="20" VaryByParam="*" %>
Now when you request the page with additional query string information, ASP.NET will examine the query string. If the string matches a previous request and a cached copy of that page exists, it will be reused. Otherwise, a new copy of the page will be created and cached separately.

To get a better idea of how this process works, consider the following series of requests:

1. You request a page without any query string parameter and receive page copy A.

2. You request the page with the parameter ProductID=1. You receive page copy B.

3. Another user requests the page with the parameter ProductID=2. That user receives copy C.

4. Another user requests the page with ProductID=1. If the cached output B has not expired, it’s sent to the user.

5. The user then requests the page with no query string parameters. If copy A has not expired, it’s sent from the cache. 

No comments:
Write comments
Recommended Posts × +