Skip to content

Instantly share code, notes, and snippets.

@mattkruskamp
Created June 7, 2012 02:38
Show Gist options
  • Save mattkruskamp/2886214 to your computer and use it in GitHub Desktop.
Save mattkruskamp/2886214 to your computer and use it in GitHub Desktop.
OutputCache for UnAuthenticated Requests Asp.Net Mvc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace Cyberkruz
{
/// <summary>
/// Custom cache attribute that excludes unauthenticated
/// users from the cache.
/// </summary>
public class UnAuthenticatedCacheAttribute : OutputCacheAttribute
{
private OutputCacheLocation? originalLocation;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// required fix because attributes are cached
// so if you hit a page unauthenticated it will
// remain unauthenticated
originalLocation = originalLocation ?? Location;
// it's crucial not to cache Authenticated content
Location = OutputCacheLocation.None;
}
else
{
Location = originalLocation ?? Location;
}
// set a filter callback. Also required because of
// the caching content.
filterContext.HttpContext.Response.Cache
.AddValidationCallback(OnlyIfAnonymous, null);
base.OnActionExecuting(filterContext);
}
/// <summary>
/// Filter method for detecting anonymous users.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="data">The data.</param>
/// <param name="status">The status.</param>
public void OnlyIfAnonymous(HttpContext httpContext,
object data, ref HttpValidationStatus status)
{
if (httpContext.User.Identity.IsAuthenticated)
status = HttpValidationStatus.IgnoreThisRequest;
else
status = HttpValidationStatus.Valid;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment