How to turn output caching off for authenticated users in ASP.NET MVC?

后端 未结 3 1379
余生分开走
余生分开走 2020-12-05 01:11

I have an ASP.NET MVC application. I need to cache some pages however only for non-authenticated users.

I\'ve tried to use VaryByCustom=\"user

3条回答
  •  猫巷女王i
    2020-12-05 01:51

    So here is what I done:

    public class NonAuthenticatedOnlyCacheAttribute : OutputCacheAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
          var httpContext = filterContext.HttpContext;
    
          if (httpContext.User.Identity.IsAuthenticated)
          {
            // it's crucial not to cache Authenticated content
            Location = OutputCacheLocation.None;
          }
    
          // this smells a little but it works
          httpContext.Response.Cache.AddValidationCallback(IgnoreAuthenticated, null);
    
          base.OnResultExecuting(filterContext);
        }
    
        // This method is called each time when cached page is going to be
        // served and ensures that cache is ignored for authenticated users.
        private void IgnoreAuthenticated(HttpContext context, object data, ref HttpValidationStatus validationStatus)
        {
          if (context.User.Identity.IsAuthenticated)            
            validationStatus = HttpValidationStatus.IgnoreThisRequest;          
          else          
            validationStatus = HttpValidationStatus.Valid;          
        }
    }
    

    Many thanks to Craig Stuntz who pointed me to correct direction and whose answer I unwittingly downvoted.

提交回复
热议问题