Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutputCache dilemma with authentication in ASP.NET MVC

I'm writing an ASP.NET MVC site that includes the possibility for users to create accounts and log in. As I also want to cache the site aggressively, I'm running into some trouble mixing caching with authentication.

On every page, at the top, if the user is logged in, I output their username, a link to their profile, and a link to log out. If they're not logged in, I output a standard login link. Plus, in the page itself, some content is not shown to unauthenticated users, while other content depends on which user is logged in.

I first attempted to solve this problem some time ago by asking the Stack Overflow team how they solved the problem. Jeff replied that they basically do no caching at all for unauthenticated users. So, I wrote an attribute that derives from OutputCacheAttribute but cancels caching if the user is logged in.

Currently, I'm using that attribute, but I'm getting incorrect results in some cases. For example, the user can visit some page, then log in, then visit the page again, only to see the login link at the top, rather than their username.

Here are some solutions that I'm considering:

  • Setting the HttpCacheability or Cache-Control type to private, rather than public. This way, the response is only cached client-side. Will this fix the problem? If it does, will this have an effect on the efficiency of caching? I've noticed that Stack Overflow seems to use public, however.
  • Setting up a VaryByCustom parameter to cache differently for each user, like in this tutorial. Will this help, while still maintaining the efficiency and effectiveness of caching?

Thanks in advance!

like image 899
Maxim Zaslavsky Avatar asked Jan 16 '11 21:01

Maxim Zaslavsky


1 Answers

Depending on the structure of your application, it may make sense to cache data rather than views.

Since views are very simple and database access usually takes most of the time required to render a page, you can get most of the benefit of output caching by caching the model in your controller, and any uncachable parts of the view will be unaffected so you can cache public content being viewed by authenticated users.

There are also ways to make output caching work with partial views, but in my opinion they add more complexity than is really justified.

like image 138
Tom Clarkson Avatar answered Oct 23 '22 20:10

Tom Clarkson