65.9K
CodeProject is changing. Read more.
Home

Expire page output cache for a specific query string parameter

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.89/5 (4 votes)

Oct 3, 2006

CPOL

1 min read

viewsIcon

30547

How to invalidate output cached page for a specific parameter?

Introduction

This article demonstrates how we can remove a cached page for a specific query string parameter. This may be required if we don't want the complete page to be removed from the cache but only those instances of the page which we want.

For example, if our page name is product.aspx and we have configured the output cache for the page like:

<%@ OutputCache duration ="600" varyByParam="ProducttId"%>

Now, we know this page will be cached depending on the value of the "ProductId" query string parameter. We call the page the first time with the following URL: http://somesite/product.aspx?productid=100. It will come from the server and not from the cache. The second call of the same URL will be serviced from the cache. If we make a call with this URL: http://somesite/product.aspx?productid=101, it will come from the server and not from the cache.

Now let's assume that we don't want our page to come from the cache for the productid 100, but want the page to come from cache for productid 101. For this, our query string will have "cache=off" if we want to expire the cache. So here, we require conditional cache expiration. For doing this, follow these steps:

Step 1: In the Page_Load event of the page, use the following code:

string strCacheKey = HttpContext.Current.Request.Url.PathAndQuery.ToString(); 
int strLen;
strLen = strCacheKey.ToUpper().IndexOf("CACHE") - 1;
if (strLen > 0)
strCacheKey = strCacheKey.Substring(0, strCacheKey.ToUpper().IndexOf("CACHE") - 1);
HttpRuntime.Cache.Insert(strCacheKey, new object());
HttpContext.Current.Response.AddCacheItemDependency(strCacheKey);

Here we are adding a cache dependency for the current request, and the dependency will be an empty object.

Step 2: When cache=off is passed in the query string, we need to expire the cache.

So in the Global.asax Application_BeginRequest event, insert the following code:

if (Request.QueryString["Cache"] != null)
{
    string resetCache = Request.QueryString["Cache"].ToString();
    if (resetCache.ToUpper() == "OFF")
    {
        //get cache key
        string strUrl = Request.Url.PathAndQuery.ToString();
        strUrl = strUrl.Substring(0, strUrl.ToUpper().IndexOf("CACHE") - 1);
        HttpRuntime.Cache.Remove(strUrl);
    }
}

And here you are. Now you can expire your output cached page for a specific productid, just by passing an extra query string parameter.

Enjoy!!!