How to Uncache current page from outputcache in ASP.Net

161 Views Asked by At

I have enabled page caching for my ASPX pages with

<%@ OutputCache Duration="7200" VaryByParam="*" Location="Server" %>

However, the next time the page is regenerated, if there happens to be an error in the page, that also gets cached, and the site continues to display the page with errors in it for the next 7200 seconds or until some dependancy flushes the cache.

Currently I tried adding the sites error log as a file dependancy, so that anytime an error is logged, pages are refreshed. However, that causes the pages to be refreshed, even when another page in the site has an error.

Question is, How can I put a piece of code in the error handling block to uncache the current page..

Pseudo code.

try
{
page load

}
catch (Exception ex)
{

// Add C# code to not cache the current page this time.

}
1

There are 1 best solutions below

3
On

You can simply use HttpResponse.RemoveOutputCacheItem as follows:

try
{
    //Page load
}
catch (Exception ex)
{
    HttpResponse.RemoveOutputCacheItem("/mypage.aspx");
}

See: Any way to clear/flush/remove OutputCache?

Another way to do that catch exception in Application_Error and use Response.Cache.AddValidationCallback, from this solution:

public void Application_Error(Object sender, EventArgs e) {
    ...

    Response.Cache.AddValidationCallback(
        DontCacheCurrentResponse, 
        null);

    ...
}

private void DontCacheCurrentResponse(
    HttpContext context, 
    Object data, 
    ref HttpValidationStatus status) {

    status = HttpValidationStatus.IgnoreThisRequest;
}