This ASP.NET MVC filter attribute is used to mark an action method whose output response will not be cached.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
namespace Mvc
{
/// <summary>
/// Action filter which disables response caching
/// </summary>
public class NoCacheAttribute : FilterAttribute, IActionFilter
{
/// <summary>
/// Called after the action method executes
/// </summary>
/// <param name="filterContext"></param>
public void OnActionExecuted(ActionExecutedContext filterContext)
{
return;
}
/// <summary>
/// Called before an action method executes
/// </summary>
/// <param name="filterContext"></param>
public void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
}
}
}
// In ASP.NET Core
// https://github.com/johnstaveley/SecurityEssentials/blob/master/SecurityEssentials/Core/Attributes/NoCacheAttribute.cs
using System;
using System.Web;
using System.Web.Mvc;
namespace SecurityEssentials.Core.Attributes
{
/// <summary>
/// SECURE: Apply this to any controller where the data is sensitive and should not be cached locally
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
}