Wednesday, June 8, 2011

Invalidate Output Cache when aspx or aspx.cs file changes

Invalidate Output Cache when aspx or aspx.cs file changes.

To do this add file dependency object to response object.

Set expires header.

Set cache location as server and private(client,proxy).

Generate Etag from file dependency(if you chnage the file
before expire header date -  this will load new file
from server) - you must set HttpCacheability .ServerAndPrivate 
for Etag to work.
Override Render event to minify HTML output.
This will save bandwidth.
In order to add this functionality 
to all the pages i have inherited page class
 and created custom Page class called MyPage.
Complete Code below.  
using  System;
using  System.Web.Caching;
using  System.Web.UI;
using  System.Web;
using  System.Reflection;
using  System.IO;
using  System.Text.RegularExpressions;
/// <summary> 
/// Summary description for MyPage 
/// </summary> 
public  partial  class  MyPage  : Page 
protected  void  Page_Init(object  sender, EventArgs  e)
string [] fileDependencies;
string  fileDependency1 = Server.MapPath(Request.Url.LocalPath);
string  fileDependency2 = Server.MapPath(Request.Url.LocalPath).Replace(".aspx" ,".aspx.cs" );
fileDependencies = new  string [] { fileDependency1, fileDependency2 };
//Uncomment before going to live. 
Response.Cache.SetVaryByCustom("browser" );
Response.Cache.SetExpires(DateTime .Now.AddDays(1));
Response.Cache.SetCacheability(HttpCacheability .ServerAndPrivate);
Response.Cache.SetValidUntilExpires(true );
//Override the page Render event to minify HTML output. 
protected  override  void  Render(HtmlTextWriter  writer)
TextWriter  output = new  StringWriter ();
base .Render(new  HtmlTextWriter (output));
String  html = output.ToString();
html = Regex .Replace(html, @"\n|\t" , " " );
html = Regex .Replace(html, @">\\s+<" , "><" ).Trim();
html = Regex .Replace(html, @"\\s{2,}" , " " );
if you want to invalidate cache manually. you can use the below method to do the task.

Response.RemoveOutputCacheItem Method (String)

1 comment:

  1. This one is perfect for encouraging kids to realize they can make a difference to their environment..
    Buy Essay Papers