Saturday 26 August 2017

Controlling asp.net caching in code

 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" %> 

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0