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

后端 未结 3 1237
一生所求
一生所求 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:41

    I want to add something to JK's answer:
    If you are setting the cache control to a more restrictive value than it already is, it is fine. (i.e: setting no-cache, when it is private)

    But, if you want to set to a less restrictive value than it already is (i.e: setting to private, when it is no-cache), the code below will not work:

    Response.Cache.SetCacheability(HttpCacheability.Private);
    

    Because, SetCacheablitiy method has this code below and sets the cache flag only if it is more restrictive:

    if (s_cacheabilityValues[(int)cacheability] < s_cacheabilityValues[(int)_cacheability]) {
        Dirtied();
       _cacheability = cacheability;
    }
    

    To overcome this in .net mvc, you need to get an instance of HttpResponseMessage and assign a CacheControlHeaderValue to its Headers.CacheControl value:

    actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue
                                       {
                                           MaxAge = TimeSpan.FromSeconds(3600),
                                           Private = true
                                       };
    

    An instance of the HttpResponseMessage is available in action filters. You can write an action filter to set cache header values like this:

    public class ClientSideCacheAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var response = actionExecutedContext.ActionContext.Response;
            response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromSeconds(9999),
                Private = true,
            };
        }
    }
    

提交回复
热议问题