views:

27

answers:

2

Is there a way to to prevent a page from being cached when the OutputCache attribute has been set on an action?

This is so that, when the page is subsequently hit, it will not store the generic error page that was returned previously.

An example below shows an instance where it would be desirable for the application not to cache the page, when it causes an exception for whatever reason (db timeout, etc).

[OutputCache(CacheProfile = "Homepage")]
public ActionResult Index()
{
  var model = new HomepageModel();

  try
  {
    model = Db.GetHomepage();
  }
  catch
  {
    //Do not want to cache this!
    return View("Error");
  }

  //Want to cache this!
  return View();
}

Update In the end, I simply needed to add the following:

filterContext.HttpContext.Response.RemoveOutputCacheItem(filterContext.HttpContext.Request.Url.PathAndQuery);

This is taken from another question.

+2  A: 

Easiest method is not to return the error view from this action method, and instead redirect to an Error action when the error occurs.

catch
{
  return RedirectToAction("Error");
}

If you cannot do that, it is possible to write an action filter that adjusts the response.cache values.

Clicktricity
Hi @Clicktricity. Thanks for your response. Unfortunately redirecting the user is not possible. I have been looking at another, similar problem - http://stackoverflow.com/questions/1043112 after discovering `RemoveOutputCacheItem`. which is more or less what I wanted.
Dan Atkinson
+1  A: 

In the end, I simply needed to add the following to the error view:

<%@ OutputCache NoStore="true" Duration="30" VaryByParam="*" %>

This sets the page to be cached for 30 seconds only.

Simples!

Dan Atkinson