Invalidate Output Cache if there is an exception on the page
Asked Answered
D

2

7

I have output caching enabled in one of the pages as follows:

<%@ OutputCache Duration="300" VaryByParam="*"%>

The issue is that sometimes there is an exception and we display an appropriate message. But this page is then Cached and other users are also seeing the exception message. For example, suppose the database times out and thus a Sql Exception is thrown. This exception is caught and a message is displayed "Error connecting to database. Please try after some time". Now this message is cached and shown to other users without even querying the database.

So what I want to do is invalidate the particular output cache if there is an exception, or perhaps not cache when there is an exception. How can this be done?

This is for ASP.NET 3.5 Webforms.

Diazotize answered 14/5, 2012 at 14:6 Comment(0)
W
5

You should be able to remove the cache item

HttpResponse.RemoveOutputCacheItem("/MyPage/MyParameter");
Woodcutter answered 14/5, 2012 at 14:27 Comment(1)
+1 but where's the best place that to trigger for all exceptions? In the application object's exception handler, or somewhere on the page, or in a finally on the controller method (if it's MVC, and if that's not too early?) or somewhere else?Jemine
U
3

Assuming your exceptions arrive to Application_Error in Global.asax, you can try following:

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;
}

This will make sure that the next response will not be served from cache but will actually make it to your page/controller.

Undergrowth answered 23/1, 2013 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.