0

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.

}
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28

1 Answers1

0

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;
}
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • Isn't this meant for pages that have already been generated and cached. ? – Al Davinci Leonardo Jul 08 '21 at 11:35
  • In this case the page is technically not generated yet, as we are in the page load event. But once it is generated it'll be cached because the <%@ outputcache ... %> directive is already inserted. I think what I'm looking for is to programmatically remove that directive in cases of exceptions. How do we do that ? – Al Davinci Leonardo Jul 08 '21 at 11:46
  • How about if you put that to `Application_Error` in `Global.asax` instead of page_load? (Assuming your exceptions can be catched in `Application_Error`) – Selim Yildiz Jul 08 '21 at 13:47