Skip to content

Instantly share code, notes, and snippets.

@peterrydetorp
Created December 21, 2019 15:44
Show Gist options
  • Select an option

  • Save peterrydetorp/2824d73ad243d873e2c0f740ddc7e2c7 to your computer and use it in GitHub Desktop.

Select an option

Save peterrydetorp/2824d73ad243d873e2c0f740ddc7e2c7 to your computer and use it in GitHub Desktop.
public class CacheControlProcessor : CacheControl
{
protected override void RunCacheControl(ActionExecutedArgs args)
{
Assert.IsNotNull(args, "args != null");
if (Sitecore.Context.Item != null)
{
if (HasRequestMethodGet(args) && DoesntHaveQuerystrings(args))
{
if (ShouldHavePublicCacheControl(args, Sitecore.Context.Item))
{
SetPublicCacheAndMaxAge(args, Sitecore.Context.Item);
return;
}
}
}
base.SetNoCacheNoStore(args);
}
private bool HasRequestMethodGet(ActionExecutedArgs args)
{
return "get".Equals(args.Context.RequestContext.HttpContext.Request.HttpMethod, StringComparison.CurrentCultureIgnoreCase);
}
private bool DoesntHaveQuerystrings(ActionExecutedArgs args)
{
var nvc = args.Context.RequestContext.HttpContext.Request.QueryString;
return nvc == null || nvc.Count == 0;
}
private bool ShouldHavePublicCacheControl(ActionExecutedArgs args, Item item)
{
if (!base.IsDisableBrowserCaching(args))
{
if (Constants.ValidTemplateIds.Contains(item.TemplateID) || TemplateIds.Model.Equals(item.TemplateID))
{
if (!HasPersonalization(item))
{
return true;
}
}
}
return false;
}
private bool HasPersonalization(Item item)
{
if (!HasPersonalizationCacheManager.TryGet(item, out bool result))
{
var device = Sitecore.Context.Device;
foreach (var rendering in item.Visualization.GetRenderings(device, false))
{
if (rendering.Settings.Rules.Count > 0)
{
result = true;
break;
}
}
HasPersonalizationCacheManager.Set(item, result);
}
return result;
}
protected void SetPublicCacheAndMaxAge(ActionExecutedArgs args, Item item)
{
var timeSpan = TemplateIds.Model.Equals(item.TemplateID) ? 900 : 3600;
if (!args.Context.RequestContext.HttpContext.Response.HeadersWritten)
{
args.Context.RequestContext.HttpContext.Response.SuppressDefaultCacheControlHeader = true;
args.Context.RequestContext.HttpContext.Response.Headers.Set("Cache-Control", $"public, max-age=0, s-maxage={timeSpan}, stale-while-revalidate={timeSpan / 2}");
args.Context.RequestContext.HttpContext.Response.Headers.Set("X-Expires", DateTime.UtcNow.AddSeconds(timeSpan).ToString("r"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment