ASP.NET Cache Page for Anonymous Users

Is there an easy way to cache the entire ASP.NET page for anonymous users (using authentication)?

Context: I create a site where the pages displayed to anonymous users are mostly completely static, but the same pages displayed to registered users are not.

Of course, I can do it manually using code, but I thought it might be better / easier / faster.

+5
source share
3 answers

You can use VaryByCustomand use a key such as username.

+1
source

asp.net MVC,

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);
}

, ( ), ( , if ).

- , . GetVaryByCustomString "", , , .

+3

, ,

:

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

        base.OnActionExecuting(filterContext);
    }  
}  

, , .

+1

All Articles