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.
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.
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.
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.
You should be able to remove the cache item
HttpResponse.RemoveOutputCacheItem("/MyPage/MyParameter");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With