Invalid output cache if there is an exception on the page

I have output caching enabled on one of the following pages:

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

The problem is that sometimes there is an exception, and we show the corresponding message. But this page is then cached, and other users also see an exception message. For example, suppose the database timed out, and thus an Sql exception was thrown. This exception is caught and the message "Error connecting to the database. Try after a while" is displayed. Now this message is cached and displayed to other users without even requesting a database.

Thus, I want to invalidate a specific output cache if there is an exception or maybe not a cache when there is an exception. How can I do that?

This is for ASP.NET 3.5 web forms.

+7
source share
2 answers

You can delete a cache item.

 HttpResponse.RemoveOutputCacheItem("/MyPage/MyParameter"); 
+5
source

Assuming your exceptions are thrown at Application_Error in Global.asax, you could try the 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 answer will not be sent from the cache, but will actually do it on your page / controller.

+2
source

All Articles