Udostępnij za pośrednictwem


Caching Multiple Versions of a Page

Depending on its complexity, when an ASP.NET page is requested, there are a number of possible responses that it can generate. For example, if you design your page with an HTML form that allows users to look up retailer locations near their home, and includes city and zip code input boxes, the page response can be different for each user. You can choose to cache a version of the page output for each city, each zip code, or both.

ASP.NET allows you to cache multiple versions of a page response. You can vary the output cache by GET query string or form POST parameters that are passed with a request, by the HTTP headers passed with a request, or by the major version of the browser that is making the request. You can also define a custom string in the page and implement how you want it to affect the response caching in your application's Global.asax file.

ASP.NET allows you to cache multiple versions of a page response declaratively by using attributes on the @ OutputCache directive and programmatically by using the properties and methods of the HttpCachePolicy class.

Specifically, the @ OutputCache directive includes three attributes that allow you to cache multiple versions of page output:

  • The required VaryByParam attribute allows you to vary the cached output depending on GET query string or form POST parameters.

  • The VaryByHeader attribute allows you to vary the cached output depending on the HTTP header associated with the request.

  • The VaryByCustom attribute allows you to vary the cached output by browser type or by a custom string that you define.

    Note   While you must include the VaryByParam attribute in any @ OutputCache directive, you can set its value to None if you do not want to use the functionality it provides.

The HttpCachePolicy class provides two properties and a method that allow you to do the same things that the aforementioned attributes do. The Boolean VaryByParams and VaryByHeaders properties allow you to specify the parameter and header names, respectively, that you want to vary the cache by. The SetVaryByCustom method allows you to define custom strings by which to vary the output cache.

For procedures and in-depth discussions on these techniques, see Caching Versions of a Page Based on Parameters, Caching Versions of a Page Based on HTTP Headers, and Caching Versions of a Page Based on Custom Strings.

See Also

@ OutputCache | Caching ASP.NET Pages | HttpApplication.GetVaryByCustomString Method | HttpCacheVaryByHeaders | HttpCacheVaryByParams | VaryByParams | VaryByHeaders