Monday, October 21, 2013

ASP.NET Programmatically Invalidating Cached Pages

Often you want to cache pages, but specific events might require you to stop using the
cached page. For example, you have multi-lingual website and once the user change the current language you want to regenerate the page and cash it again, if you use a parameter for the language it's too easy to do it by setting the VaryByParam property in the page directive

<%@ OutputCache Duration="15" VaryByParam="lang" %>

In this example the page will be cashed for the next 15 minutes unless the Parameter lang is changed, then the page will be regenerated.

but what if you use the session to store the current language, one of the approach to handle it by determining Whether to Return a Cached Page Prior to Rendering:

- In the page load set a call back function for determining whether the page should be regenerated or just use the cashed version.


Sample of C# Code
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(ValidateCacheOutput), null);
}

- Now write down the function to be called

Sample of C# Code
public static void ValidateCacheOutput(HttpContext context, Object data,ref HttpValidationStatus status) 
     if (Session["LangChanged"] != null) 
     { 
         string currentLang = Session["LangChanged"].ToString(); 
         if (currentLang == "Yes") 
         status = HttpValidationStatus.Invalid;  
Session["LangChanged"] = Null; 
}
else   if (currentLang == "No")
{
status = HttpValidationStatus.Valid;
}  
else  
         status = HttpValidationStatus.IgnoreThisRequest; 
}
- When the user fired change language button, all you have to do is to set the Session to Yes,
Session["LangChanged"]  = "Yes";
Notice that this code sample uses logic to specify one of the HttpValidationStatus values to
control how the page is cached:
■ HttpValidationStatus.Invalid This causes the cache to be invalidated so that the page
is dynamically generated. The newly generated page is stored in the cache, replacing
the earlier cached version.
■ HttpValidationStatus.IgnoreThisRequest This causes the current page request to
be dynamically generated without invalidating the previously cached version of the
page. The dynamically generated page output is not cached, and future requests
might receive the previously cached output.

■ HttpValidationStatus.Valid This causes ASP.NET to return the cached page.