Cache-control: no-store, must-revalidate not sent to client browser in IIS7 + ASP.NET MVC

后端 未结 3 1241
一生所求
一生所求 2020-12-08 09:57

I am trying to make sure that a certain page is never cached, and never shown when the user clicks the back button. This very highly rated answer (currently 1068 upvotes) s

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 10:53

    If you need these headers globally in your MVC application. Add this class.

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class CustomHeaders : System.Web.Mvc.ActionFilterAttribute
    {
        [OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            context.RequestContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            context.RequestContext.HttpContext.Response.Cache.AppendCacheExtension("no-store, must-revalidate");
            context.RequestContext.HttpContext.Response.AppendHeader("Pragma", "no-cache");
            context.RequestContext.HttpContext.Response.AppendHeader("Expires", "0");
    
            base.OnActionExecuted(context);
        }
    }
    

    For global use add it to the FilterConfig.

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new CustomHeaders());
        }
    }
    

    Or only use these headers on a specific controller.

    [Authorize]
    [CustomHeaders]
    public class HomeController : Controller
    {
        [AllowAnonymous]
        public ActionResult Index()
    

    Side note: you can use IIS and web.config for other headers. For example on static content like your bundles (jquery,bootstrap). Look for these sections customheaders, staticcontent.

提交回复
热议问题