3

i want to use output caching to avoid hitting my db over and over with the same static query but my controllers have parameters that uniquely define the post.

How can i factor in my parameters and still support output caching in asp.net-mvc?

leora
  • 188,729
  • 360
  • 878
  • 1,366

1 Answers1

7

Check out the VaryByParam property of the OutputCache attribute.

[OutputCache(Duration=int.MaxValue, VaryByParam="id")]
public ActionResult Details(int id)
{
}

For each unique id value, a unique cache instance will be created.

Edit:

If your caching needs go beyond simple VaryByParam scenarios then take a look at VaryByCustom. This will allow you to setup the scenarios as you see fit (cached version for logged in vs. not logged in user, etc. etc.)

Khepri
  • 9,547
  • 5
  • 45
  • 61
  • does that work if my parameter is an object with a number of properties ?? – leora Jun 14 '11 at 11:42
  • You can but there are some side effects that you should be aware of. See this post for example: http://stackoverflow.com/questions/5144592/partial-page-caching-and-varybyparam-in-asp-net-mvc-3 So you can pass an object and do VaryByParam="*" for example, but in the end the recommendation (or my opinion, I should say) is to have some unique primitive value or set of primitives that you can use. – Khepri Jun 14 '11 at 14:20
  • thanks for the link. To clarify, in the example link, would that partial page be cached as long as the Ids match. What if they ids matched but the property of content changed? Would that still produce the cached result. If so, that is NOT what i want. I want the caching to be a 1:1 mapping with each unique object. I guess i could go with the Override the ToString() on the object to be a unique string factoring in all of the properties of the string. That should work, correct? – leora Jun 15 '11 at 11:08
  • If the Id's matched, the content for the cached version would be retrieved. The newer content would be retrieved once the duration for the cached item had expired. In your scenario, it sounds like you want a separate cache copy for any change, however small, to the object? If so, just do VaryByParam="*" and since you have the one object param which performs a ToString() conversion, you should (you'll have to test it out, I've never personally worked with objects and output caching in this manner) get a separate cache for every change, like you want. – Khepri Jun 15 '11 at 14:54