Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Controlling caching in code - Part 121

Suggested Videos
Part 118 - Difference between user controls and custom controls
Part 119 - Caching in ASP.NET
Part 120 - Caching multiple responses for a single webform

The basics of caching are discussed in Part 119, and caching multiple responses for a single webform are discussed in Part 120. In both of these videos, we discussed about  controlling caching within the Webform HTML using the OutputCache directive. In this video, we will discuss about controlling caching in code.

"Cache" property of the "Response" object, can be used to control caching in code. "Response.Cache" property returns the "HttpCachePolicy" object, which can be used in code just like the "OutputCache" directive is used in webform's HTML.

Copy and paste the following HTML on the webform.
<div style="font-family: Arial">
    Server Time : 
    <asp:Label ID="Label1" runat="server" Font-Bold="true" ></asp:Label>
    <br /><br />
    Client Time:
        <script type="text/javascript">

Copy and paste the following code in the code-behind file
1. SetExpires() method, is used to set the duration for which we want to cachs the webform. This is similar to the "Duration" attribute of the "OutputCache" directive.
2. Response.Cache.VaryByParams["None"] = true. This is similar to setting VaryByParam="None" for the "OutputCache" directive.
3. To control the location where items are cached, we can use "Location" attribute of the "OutputCache" directive, and SetCacheability() method in code.

protected void Page_Load(object sender, EventArgs e)
    Label1.Text = "This page is cached by the server @ " + DateTime.Now.ToString();
    Response.Cache.VaryByParams["None"] = true;

Equivalent OutputCache settings 
<%@ OutputCache Duration="60" VaryByParam="None" Location="Server" %>


  1. one more attribute should be set of response in the above coding that is



  2. I agree. Add: Cache.SetValidUntilExpires(true);


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.