Dan Atkinson
Dan Atkinson

Reputation: 11699

Prevent returned view being cached when an error occurs

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.

Upvotes: 2

Views: 1478

Answers (2)

Dan Atkinson
Dan Atkinson

Reputation: 11699

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!

Upvotes: 1

Clicktricity
Clicktricity

Reputation: 4209

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.

Upvotes: 2

Related Questions