To cause a page to be added to the output cache, you establish an expiration policy for that page. You can do this declaratively or programmatically.
To set output-cache expirations for a page declaratively
Include an directive in the ASP.NET page (.aspx file) whose response you want to cache. Set the attribute to a positive numeric value, and set the attribute to a value.
The directive sets the Cache-Control header to Any by default.
For example, the following @В OutputCache directive sets the page's expiration to 60 seconds:
В Copy Code
<%@ OutputCache Duration="60" VaryByParam="None" %>
You must include a VaryByParam attribute when using the @ OutputCache directive or a parser error will occur. If you do not want to use the functionality offered by the VaryByParam attribute, set its value to "None". For more information, see Caching Multiple Versions of a Page.
To set output-cache expirations for a page programmatically
In the page's code, set the expiration policy for the page on the property of the object.
If you set expirations for a page programmatically, you must set the Cache-Control header for the cached page as well. To do so, call the method and pass it the enumeration value Public.
The following code example sets the same cache policy as the @В OutputCache directive does in the preceding procedure.
C#В Copy Code
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true);
Visual BasicВ Copy Code
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)) Response.Cache.SetCacheability(HttpCacheability.Public) Response.Cache.SetValidUntilExpires(True)
When the cached page expires, the subsequent request for the page causes a dynamically generated response. This response page is cached for the specified duration.