ASP.Net MVC Framework Server-Side HTML Caching Techniques

The ASP.NET Framework provides many out-of-the-box techniques to cache data on the server useful for improving system performance and reducing the load on the content providing servers.

ASP.NET not only provides server-side data caching techniques but also provides client-side rendered content caching, called Output Caching. This helps to cache the rendered HTML on the client side. Caching allows subsequent requests for the same page to be satisfied from cache itself.

ASP.NET provides the ability to cache at various levels like cache the page at the browser that is making the request at the Web server responding to the request and at any other cache-capable devices, such as proxy servers, that are in the request or response stream.

ASP.NET provides the ability to cache either an entire page or parts of the page, called fragment caching. We also have the many techniques described here.

1. Cache Versions of a Page Using Requesting Browser

Sometimes web applications contain a page that creates various output based on the type of the requesting browser, caching this page's output by the major version of the browser that requests the page also possible with ASP.NET.

Declaratively

  1. <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="browser" %>
Programmatically 

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Response.Cache.SetExpires(DateTime.Now.AddMinutes(1d));  
  4.     Response.Cache.SetCacheability(HttpCacheability.Public);  
  5.     Response.Cache.SetValidUntilExpires(true);  
  6.     Response.Cache.SetVaryByCustom("browser");  
  7. }

2. Cache Versions of a Page Using Parameters

In modern web development, most pages are dynamic; the same page may render various content based on the query string parameters. Caching these pages will also help to increase the site performance.

Let us say we have an air ticket booking site that retrieves the codes of all the airports based in the country, or sometimes even a country and state. Caching these pages will always boost the performance of the application.

Declaratively

  1. <%@ OutputCache="" Duration="60" VaryByParam="Country" %>  
  2. <%@ OutputCache="" Duration="60" VaryByParam="Country;State" %>   

Programmatically

  1. Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));  
  2. Response.Cache.SetCacheability(HttpCacheability.Public);  
  3. Response.Cache.SetValidUntilExpires(true);  
  4. Response.Cache.VaryByParams["Country"] = true;   

Or

  1. Response.Cache.SetExpires(DateTime.Now.AddMinutes(1.0));  
  2. Response.Cache.SetCacheability(HttpCacheability.Public);  
  3. Response.Cache.SetValidUntilExpires(true);  
  4. Response.Cache.VaryByParams["Country"] = true;  
  5. Response.Cache.VaryByParams["State"] = true;

3. Cache Versions of a Page Using HTTP Headers

ASP.NET allows you to cache multiple versions of a page depending on the value of an HTTP header; either single header, multiple or for all hears also possible to cache.

Declaratively

  1. <%@ OutputCache Duration="60" VaryByParam="None" VaryByHeader="Accept-Language" %>
Programmatically
  1. Response.Cache.SetExpires(DateTime.Now.AddMinutes(1d));  
  2. Response.Cache.SetCacheability(HttpCacheability.Public);  
  3. Response.Cache.SetValidUntilExpires(true);  
  4. Response.Cache.VaryByHeaders["Accept-Language"] = true;   

For all headers

  1. Response.Cache.SetExpires(DateTime.Now.AddMinutes(1d));  
  2. Response.Cache.SetCacheability(HttpCacheability.Public);  
  3. Response.Cache.SetValidUntilExpires(true);  
  4. Response.Cache.VaryByHeaders["VaryByUnspecifiedParameters"] = true; 

4. Cache Versions of a Page Using Custom Strings

ASP.NET also supports output caching based on various strings returned by a method that you define in the code. When cached pages are based on custom strings, first specify an identifier for the custom string to use. Then create a method in the application's Global.asax file that accepts the identifier and returns a value to vary the output cache by. In the application's Global.asax file, override the GetVaryByCustomString method to specify the behavior of the output cache for the custom string.

Declaratively

  1. <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="minorversion" %>
Programmatically
  1. public override string GetVaryByCustomString(HttpContext context, string arg)  
  2. {  
  3.     if(arg == "minorversion")  
  4.     {  
  5.         return "Version=" + context.Request.Browser.MinorVersion.ToString();  
  6.     }  
  7.     return base.GetVaryByCustomString(context, arg);  
  8. } 

5. Validate the paged cache

When a request comes for a cached page, ASP.NET determines whether the cached output is still valid based on the cache policy defined in the page. If the output is valid then the cached output is sent to the client. However, ASP.NET provides the ability to run validation code during this validation check using a validation callback, to check whether the page is still valid.
 
The following handler named "isCacheValid" determines whether the query string variable status contains the values "invalid" or "ignore". If the status value is "invalid" then the method returns Invalid and the page is invalidated in the cache. If the status value is "ignore" then the method returns "IgnoreThisRequest" and the page is left in the cache but a new response is generated for this request.

  1. public static void isCacheValid (HttpContext context, Object data, ref HttpValidationStatus status)  
  2. {  
  3.     if (context.Request.QueryString["Status"] != null)  
  4.     {  
  5.         string pageStatus = context.Request.QueryString["Status"];  
  6.         if (pageStatus == "invalid")  
  7.             status = HttpValidationStatus.Invalid;  
  8.         else if (pageStatus == "ignore")  
  9.             status = HttpValidationStatus.IgnoreThisRequest;  
  10.         else  
  11.             status = HttpValidationStatus.Valid;  
  12.     }  
  13.     else  
  14.         status = HttpValidationStatus.Valid;  
  15. }

The following defines an event handler of type "HttpCacheValidateHandler" in the page event life cycle and includes code that checks the validity of the cached page response.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.    Response.Cache.AddValidationCallback(  
  4.    new HttpCacheValidateHandler(isCacheValid), null);  
  5. } 
6. Cache Page Output with File, Key/Item, SQL Dependencies

Sometimes ASP.NET gets data from a XML file or another key/item, some table updates. If something gets changed on these dependencies then we should invalidate the already cached data of these inputs.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     string fileDependencyPath = Server.MapPath("biztalkOutPut.xml");  
  4.     Response.AddFileDependency(fileDependencyPath);  
  5.     // Set additional properties to enable caching.  
  6.     Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));  
  7.     Response.Cache.SetCacheability(HttpCacheability.Public);  
  8.     Response.Cache.SetValidUntilExpires(true);  
  9. }

You cannot use these methods from an ASP.NET user control. However, in any user control that specifies the '@OutputCache' directive you can create a file dependency and assign it to the "Dependency" property. You can also have multiple file dependencies to invalidate the cache.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     string[] fileDependencies;  
  4.     string fileDependency1 = Server.MapPath("MyFile.txt");  
  5.     string fileDependency2 = Server.MapPath("biztalkOutPut.xml");  
  6.     fileDependencies = new String[] { fileDependency1, fileDependency2 };  
  7.     Response.AddFileDependencies(fileDependencies);  
  8. }

Key/Item Dependency

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Response.AddCacheItemDependency("anotheritem");  
  4.     Response.Cache.SetExpires(DateTime.Now.AddSeconds(10));  
  5.     Response.Cache.SetCacheability(HttpCacheability.Public);  
  6.     Response.Cache.SetValidUntilExpires(true);  
  7. } 

SQL Dependency

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     SqlDependency.Start(<Connection string>);  
  4.     using (SqlConnection connection = new SqlConnection((<Connection string>)  
  5.     {  
  6.         using (SqlCommand command = new SqlCommand(<SQL Statement>, connection))  
  7.         {  
  8.             SqlCacheDependency dependency = new SqlCacheDependency(command);  
  9.             int numberOfMinutes = 3;  
  10.             DateTime expires = DateTime.Now.AddMinutes(numberOfMinutes);  
  11.             Response.Cache.SetExpires(expires);  
  12.             Response.Cache.SetCacheability(HttpCacheability.Public);  
  13.             Response.Cache.SetValidUntilExpires(true);  
  14.             Response.AddCacheDependency(dependency);  
  15.             connection.Open();  
  16.             GridView1.DataSource = command.ExecuteReader();  
  17.             GridView1.DataBind();  
  18.         }  
  19.     }  
  20. } 

7. Output Caching and ASP.NET MVC

With the introduction of MVC controllers in ASP.NET the caching framework has been extended to support the content caching at the controller level. Because each ActionResult in the controller creates a view and caching that view will make the application performance increase.

The ASP.NET MVC Framework provides the OutputCacheAttribute attribute to an action filter that tells ASP.NET MVC to add the rendered results of the controller action to the output cache. This attribute has the same number of parameters that we have seen to provide support of caching at the controller level.

  1. CacheProfile: The name of the output cache policy to use. This allows defining a global location to define all the caching policies for the OutputCacheAttribute, instead of defining for each ActionResult in the controller. It is in the Web.Config.
    1. <caching>  
    2.    <outputCacheSettings>  
    3.       <outputCacheProfiles>  
    4.       <addname="GetDetails"duration="3600"varyByParam="id"/>  
    5.       <addname="CachedDateTime"duration="60"varyByParam="none"/>
          </outputCacheProfiles>  
    6.  </outputCacheSettings>  
    7. </caching> 
  2. Duration: The amount of time in seconds to cache the content. The default is 60 seconds.
    1. [OutputCache(Duration=60, VaryByParam="none")]  
    2. public ActionResult CachedDateTime()  
    3. {  
    4.    ViewBag.Message = DateTime.Now.ToString();  
    5.    return View();  
    6.  
  3. Enabled: Enables/disables the output cache for the current content.
  4. Location: The location of where to cache the content. The default is "Any". The other possible values are "Client", "Down stream", "Server", "None", or "ServerAndClient".
    1. [OutputCache(Duration = 3600, VaryByParam = "none", Location =OutputCacheLocation.Client, NoStore =true)]  
    2. public ActionResult LoginUser()  
    3. {  
    4.    ViewBag.Message = "The current user name is " + User.Identity.Name;  
    5.    return View();  
    6. } 
  5. NoStore: Enables/disables HTTP Cache-Control
  6. SqlDependency: The database and table name pairs that the cache entry depends on.
  7. VaryByContentEncoding:  A comma-delimited list of character sets (content encodings) that the output cache uses to vary the cache entries.
  8. VaryByCustom: A list of custom strings that the output cache uses to vary the cache entries.
  9. VaryByHeader: A comma-delimited list of HTTP header names used to vary the cache entries.
  10. VaryByParam: A semicolon-delimited list of form POST or query string parameters that the output cache uses to vary the cache entry. The most useful one in this list. Allow caching multiple versions of the view with different content.
    1. [OutputCache(Duration = 600, VaryByParam = "id")]  
    2. public ActionResult GetDetails(string id)  
    3. {  
    4.     var auction = _productDetails.Find<Auction>(id);  
    5.     return View("ProductDetails", auction);  
    6. }


Similar Articles