How to switch off caching for MVC requests but not for static files in IIS7?

前端 未结 2 728
忘了有多久
忘了有多久 2020-12-31 23:32

I\'m developing an ASP.NET MVC application. Most of the controller actions are not supposed to be cached. Because of this I output no-cache headers in Application_Begi

2条回答
  •  遥遥无期
    2021-01-01 00:26

    You could have a Caching filter attribute that applies this to all your actions (either through a base controller or explicitly on each controller or action). This would not the apply to you static files.

    Possible [CacheFilter]:

    using System;
    using System.Web;
    using System.Web.Mvc;
    
        public class CacheFilterAttribute : ActionFilterAttribute
        {
    
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
    
                cache.SetExpires(DateTime.UtcNow.AddDays(-1));
                cache.SetValidUntilExpires(false);
                cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
                cache.SetCacheability(HttpCacheability.NoCache);
                cache.SetNoStore();
            }
        }
    

    As an aside could you even deliver your static files from a different domain, like SO do with sstatic.net, which would eliminate your problem as a side effect.

提交回复
热议问题