Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching content only for non-authenticated users

For a web-site, I want to cache the pages ONLY for users who are not authenticated - authenticated users do not get cached content (since they will be updating and need to see results right away).

I know how to vary the cache for each user using VaryByCustom: Link1 Link2

...But I can't figure out how to turn off caching entirely for authenticated users.

What to do?

Edit

The code below has a problem if there is already a cached version of the page from an unauthenticated user. Basically the authenticated user will be served the unauthenticated view of things.

However, this link here has solution that works: Link

like image 244
Kjensen Avatar asked Feb 04 '11 12:02

Kjensen


2 Answers

Use this as a global action filter.

public class NoCacheForAuthenticatedUsersAttribute: ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if(filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        }
    }
}
like image 129
smartcaveman Avatar answered Oct 13 '22 06:10

smartcaveman


Use HttpCachePolicy.AddValidationCallback.

See: http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.addvalidationcallback.aspx

like image 22
Haacked Avatar answered Oct 13 '22 07:10

Haacked