我有一个ASP.NET MVC应用程序.我需要缓存一些页面,但只对非验证用户.
我试图使用VaryByCustom =“user”与以下GetVaryByCustomString实现:
public override string GetVaryByCustomString(HttpContext context,string custom) { if (custom == "user") { if (context.User.Identity.IsAuthenticated) { return context.User.Identity.Name; } else { return ""; } } return base.GetVaryByCustomString(context,custom); }
然而,这并不是我所需要的,因为网页仍然被缓存.只有不同的是,现在是为每个用户单独缓存.
一个可能的解决方案是每当用户被认证时返回Guid.NewGuid(),但是对我来说看起来像是浪费大量资源.
那么你有什么技巧给我吗?
解决方法
所以这里是我做的:
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; } }
非常感谢Craig Stuntz谁指出我正确的方向,他的回答我不知不觉中被低估了.