Any way to clear/flush/remove OutputCache?

You can use the VaryByCustom parameter for this.

In your user control you would have the following:

<%@ OutputCache Duration="1000" VaryByParam="None" VaryByCustom="MyKey" %>

Then you would override the GetVaryByCustomString method in your Global.asax like so:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg == "MyKey")
    {
        object o = context.Current.Application["MyGuid"];
        if (o == null)
        {
            o = Guid.NewGuid();
            context.Current.Application["MyGuid"] = o;
        }
        return o.ToString();
    }
    return base.GetVaryByCustomString(context, arg);
}

Finally in MyPage.aspx you would do this:

Application["MyGuid"] = Guid.NewGuid();

How does this work?

Whenever your control is cached, it is associated with a string (the string returned from the GetVaryByCustomString method when your control’s VaryByCustom key is passed into it).

Whenever the control is subsequently used, GetVaryByCustomString is called again. If the returned string matches a cached version of the control, then the cached version is used.

In our case, “MyKey” is passed into GetVaryByCustomString and it returns whatever is stored in Application["MyGuid"].

Whenever MyPage.aspx is called, it changes Application["MyGuid"] to a new random value.

When your control is next used the GetVaryByCustomString method will return the new value, and because there is no cached version of the control associated with that value, the control will be regenerated. (The control will then be cached and associated with the new value, to persist until the next call to MyPage.aspx etc)

There’s an overview here.

Leave a Comment