To add a page to the output cache, you need to create an expiration Policy for the page. This can be achieved through declaration or programming.
Set the expiration time of the output cache for the page in declarative Mode
Include the @ OutputCache command in the ASP. NET page (. aspx file) in which you want to cache the response. Set the Duration attribute to a positive value and the VaryByParam attribute to a value.
Note:
By default, the @ OutputCache command sets the Cache-Control header to Any.
For example, the following @ OutputCache command sets the page expiration time to 60 seconds:
Copy code
<% @ OutputCache Duration = "60" VaryByParam = "None" %>
Note:
When using the @ OutputCache command, a VaryByParam attribute must be included; otherwise, a analyzer error will occur. If you do not want to use the functions provided by the VaryByParam attribute, set the value to "None ". For more information, see multiple versions on the cache page.
Set the expiration time of the output cache for pages in programming mode
In the code on this page, set the expiration policy for this page in the Cache attribute of the Response object.
Note:
If you set the page expiration time programmatically, you must also set the Cache-Control header for the cached page. Therefore, call the SetCacheability method and pass the HttpCacheability enumerated value Public to it.
The following code example sets the same cache policy as the @ OutputCache command in the previous process.
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 cache page expires, future requests to this page will cause a dynamic response. The response page is cached within the specified duration.