How to: Cache Versions of a Page Using Parameters
There are times when you want to cache a page, but the page might generate different output based on the value of a query string parameter or values sent with the page on postback. For example, if you have a page that shows locations of stores based on a user's state, the page might accept a "state" query string value that generates a different version of the page for each state.
You can cache multiple versions of page responses based on the parameters sent as query string values or form post values.
ASP.NET treats query string values or form post values with identical key/value pairs as identical for caching purposes, regardless of the order in which the parameters are passed. However, for caching purposes, parameter names are case-sensitive and ASP.NET will cache different versions of a page for uppercase and lowercase parameter names and values.
To cache multiple versions of page output declaratively using parameters
In the ASP.NET page, include andirective with a Duration attribute. The Duration attribute is required and must be set to an integer greater than zero.
In thedirective, include a VaryByParam attribute and set its value to the name of the query string or form post parameter that you want to vary the page by.
The following code example caches the page for 60 seconds and specifies that different versions of the page output will be cached based on the City query string value or form post parameter.
<%@ OutputCache Duration="60" VaryByParam="City" %>
If you want to vary the output cache by multiple parameters, include a list of parameter names separated by semicolons (;). If you want to vary the cache by all parameter values, set the VaryByParam attribute to an asterisk (*). The following code example shows how to vary the page output by City and ZipCode parameters.
To cache multiple versions of page output programmatically using parameters
In the page's Page_Load event, call theand methods on the property of the object.
Specify the parameter name as the argument for the Response object'sproperty, and set the property to true.
The following code example shows how to cache multiple versions of a page when requests arrive at the server with different values for the Zip parameter.
Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true); Response.Cache.VaryByParams["Zip"] = true;
Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0)) Response.Cache.SetCacheability(HttpCacheability.Public) Response.Cache.SetValidUntilExpires(True) Response.Cache.VaryByParams("Zip") = True
If you want to vary the cached content by multiple parameters, set the VaryByParams property multiple times. If you want to vary the cached content by all header values, set theattribute to an asterisk (*). The following code example shows how to vary the page output by City and Zip parameters.