Subscribe

RSS Feed (xml)

Page Output Caching

Page output caching can be accomplished declaratively using a page @


OutputCache


directive or programmatically using the Response.Cache API.The following code samples


are equivalent:


<script runat="server">


Sub Page_Load (sender As object, e As EventArgs)


Response.Cache.SetExpires(DateTime.Now.AddSeconds(100))


Response.Cache.SetCacheability(HttpCacheability.Public)


Response.Cache.SetValidUntilExpires(true)


' Set the timestamp


timestamp.Text = DateTime.Now.ToString()


End Sub


</script>


<asp:Label id="timestamp" runat="server" />



Or




<%@ OutputCache Duration="100" VaryByParam="none" %>


<script runat="server">


Sub Page_Load(sender As Object, e As EventArgs)


timestamp.Text = DateTime.Now.ToString()


End Sub


</script>


<asp:Label id="timestamp" runat="server" />


Comments


As you can clearly see in the code sample, the page @OutputCache directive is much easier


to implement. However, the lower-level Response.Cache API provides more flexibility


when necessary. In either case, the content for the response is generated once and


stored in memory before being sent back to the client.The contents are never written to


disk, but instead are kept in memory within the application using the Cache API.


In the @OutputCache directive example, the Duration and VaryByParam attributes are


required (if they are not specified, an exception is thrown detailing the requirements of


these attributes).The Duration attribute is a time dependency, in seconds, used to control


the lifetime of the cached response in memory.The VaryByParam attribute specifies


which parameters (in the Request.Params collection) should cause separate versions of


the page to be stored in the cache.


The SetValidUntilExpires() method on Response.Cache is used to control a


nuance of HTTP caching. By default, this method is set to true when using the


@OutputCache directive. Conversely, the default is false when using the


Response.Cache API. SetValidUntilExpires() controls how ASP.NET honors cache


invalidation headers sent by browsers.When users click the Refresh button in the browser,


the browser sends an HTTP header to the server specifying that the requested content


cannot come from a cache.When SetValidUntilExpires() is true, the HTTP


cache invalidation request sent by the browser is ignored and the request can be served


from the cache; when false, the HTTP cache invalidation request is honored and the


request is removed from the cache. It's recommended to always set this to true to guarantee


that the server can respond from the cache, otherwise a simple refresh in the


browser can remove the item from the cache.

No comments:

Archives

Variety in the Web World