Mark Johnson
Mark Johnson

Reputation: 159

Problematically Invalidate the IIS Output Cache

My content is generally pre-rendered data that is derived from a database. All the pages load once and are cached. If the data in the database changes, the cache should be invalidated for certain pages.

Is there a way to reset the IIS Output Cache programmatically, on a button click for example?

Upvotes: 0

Views: 410

Answers (1)

Tasos K.
Tasos K.

Reputation: 8079

Output cache has a few parameters that you can use to handle cache objects VaryByParam, VaryByControl, and VaryByCustom.

VaryByParam caches the object based on the parameters of the request e.g. Query String values and, in case of a POST / PostBack the POST / PostBack values.

VaryByControl caches the object based on the values of the listed controls in the VaryByControl attibute.

VaryByCustom is a way to set custom logic to your caching mechanism. Here is an example on how it could help in your scenario.

You are using the following directive in the pages and controls you are caching. Note the use of VaryByParam="none".

<%@ OutputCache Duration="900" VaryByParam="none" VaryByCustom="somevariablename" %> 

In your Global.asax file you add the following function:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg == "somevariablename")
    {
        return GetCustomCacheIdentifier();
    }
    return base.GetVaryByCustomString(context, arg);
}

This function fires every time a page or a control has an OutputCache directive. When the arg parameter is set to the value you have set in VaryByCustom you can return some value.

If the value is the same, IIS will return the cached version of the page, where as if you return a new value the pages will be rendered again.

For example, you can return a counter that will initially be set at 0, and increment that counter whenever there is a change in the database.

Upvotes: 1

Related Questions