Stephen2

CustomPageRouteHandler - inherit from Feather

Feb 2nd, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1. namespace SitefinityWebApp.Websilk
  2. {
  3.     public class CustomPageRouteHandler : MvcPageRouteHandler
  4.     {
  5.         protected override bool ApplyServerCache(HttpContextBase context, OutputCacheProfileElement profile, PageSiteNode siteNode)
  6.         {
  7.             var allowCaching = false;
  8.  
  9.             //Never cache POST requests, and never cache if the USER isn't null
  10.             if (context.Request.RequestType != "POST" && !ClaimsManager.GetCurrentIdentity().IsAuthenticated)
  11.             {
  12.                 //NB: this always returns true, but maybe that changes in future?
  13.                 allowCaching = base.ApplyServerCache(context, profile, siteNode);
  14.  
  15.                 //Need to use reflection as .NET does not allow for setting false value once we've set it to true
  16.                 var headers = context.Response.Cache.VaryByHeaders;
  17.                 var headersCollection = headers.GetType().GetField("_headers", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(headers) as NameObjectCollectionBase;
  18.  
  19.                 if (headersCollection != null)
  20.                 {
  21.                     var method = headersCollection.GetType().GetMethod("BaseRemove", BindingFlags.NonPublic | BindingFlags.Instance);
  22.                     method.Invoke(headersCollection, new object[] { "User-Agent" });
  23.                 }
  24.  
  25.                 //Extra cache callback check... It should never return cached item for logged in users
  26.                 context.Response.Cache.AddValidationCallback(IgnoreCacheRequestIfLoggedIn, null);
  27.             }
  28.             else
  29.             {
  30.                 //Never cache POST or Authenticated requests
  31.                 context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  32.             }
  33.  
  34.             return allowCaching;
  35.         }
  36.  
  37.         static void IgnoreCacheRequestIfLoggedIn(HttpContext context, object data, ref HttpValidationStatus status)
  38.         {
  39.             //Ignore cache for logged in users, but everyone else is still valid
  40.             //NB: There's much extra logic in the base Sitefinity PageRouteHandler
  41.             status = ClaimsManager.GetCurrentIdentity().IsAuthenticated ? HttpValidationStatus.IgnoreThisRequest : status;
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment