Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalidate Output Cache if there is an exception on the page

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.

like image 704
shashi Avatar asked May 14 '12 14:05

shashi


People also ask

How to use Output cache in MVC?

In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.

Where is Output cache stored?

The output cache is located on the Web server where the request was processed. This value corresponds to the Server enumeration value. The output cache can be stored only at the origin server or at the requesting client. Proxy servers are not allowed to cache the response.

How does Output cache work?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.


2 Answers

You should be able to remove the cache item

HttpResponse.RemoveOutputCacheItem("/MyPage/MyParameter");
like image 133
Jamie Dixon Avatar answered Oct 20 '22 01:10

Jamie Dixon


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.

like image 28
Dmitry Avatar answered Oct 20 '22 00:10

Dmitry