2

I have an MVC application with approx 20 controllers.

In this application I want to cache certain views (mostly partials) for 60 seconds, i.e. the result would only change once per minute, even if the underlying data changed during that minute.

Seems simple enough.

The complication is that the partials show different data dependant on the currently logged in user. How can I make sure that the cache is per user using MVC3?

tereško
  • 58,060
  • 25
  • 98
  • 150
KingCronus
  • 4,509
  • 1
  • 24
  • 49
  • Duplicate of: http://stackoverflow.com/questions/290098/asp-net-mvc-caching-vary-by-authentication – hometoast Nov 16 '12 at 12:53
  • possible duplicate of [OutputCache controller attribute vary by user role? Is this possible in .net MVC?](http://stackoverflow.com/questions/2289941/outputcache-controller-attribute-vary-by-user-role-is-this-possible-in-net-mvc) – hometoast Nov 16 '12 at 12:55

1 Answers1

3

You can use OutputCacheAttribute to affect output caching on on a controller or action-by-action basis, and use VaryByCustom.

[OutputCache(Duration = 60, VaryByParam = "*", VaryByCustom="userName")]

Place that on the controllers, then go into your Global.asax.cs and override GetVaryByCustomString:

public override string GetVaryByCustomString(HttpContext context, string arg) 
{ 
  if(arg.ToLower() == “username” && context.User.Identity.IsAuthenticated) return context.User.Identity.Name;

  return base.GetVaryByCustomString(context, arg); 
}
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
  • When you say "Place that on the controllers" I assume you mean per actionmethod? – KingCronus Nov 16 '12 at 13:01
  • 1
    You have three options: 1) Place it on individual actions 2) Place it on a controller, which will result in each action inheriting that filter 3) Set it up as a global filter, which will result in it getting applied to every action without having to modify your controllers at all. http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvcglobalanddynamicactionfilters.aspx – moribvndvs Nov 16 '12 at 13:18