Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Controlling asp.net 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:
    <b>
        <script type="text/javascript">
            document.write(Date());
        </script>
    </b>
</div>



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.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.VaryByParams["None"] = true;
    Response.Cache.SetCacheability(HttpCacheability.Server);
}

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

3 comments:

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

    Response.Cache.SetValidUntilExpires(true);

    thanks

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

    ReplyDelete
  3. I agree also. Add: Response.Cache.SetValidUntilExpires(true);

    ReplyDelete

It would be great if you can help share these free resources