Cache ASP.NET page for anonymous users only

孤街浪徒 提交于 2019-12-05 10:44:57

You could use VaryByCustom, and use a key like username.

I'm using asp.net MVC, so I did this in my controller

if (User.Identity.IsAuthenticated) {
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
    Response.Cache.SetNoStore();
    Response.Cache.SetNoServerCaching();
}
else {
    Response.Cache.VaryByParams["id"] = true; // this is a details page
    Response.Cache.SetVaryByCustom("username"); // see global.asax.cs GetVaryByCustomString()
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetCacheability(HttpCacheability.Server);
    Response.Cache.SetValidUntilExpires(true);
}

The reason I did it this way (instead of declaratively) was I also needed the ability to turn it on and off via configuration (not shown here, but there's an extra check in the if for my config variable).

You still need the vary by username, else you'll not execute this code when a logged in user appears. My GetVaryByCustomString function returns "anonymous" when not authenticated or the users name when available.

There is nothing stopping you from extending the existing attribute with the desired behaviour,

for example:

public class AnonymousOutputCacheAttribute : OutputCacheAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    {
       if(filterContext.HttpContext.User.Identity.IsAuthenticated)
          return;

        base.OnActionExecuting(filterContext);
    }  
}  

Haven't tested this, but I don't see reason why this shouldn't work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!