Search code examples
asp.net-mvccachingoutputcache

MVC clear cache after certain time of day


I have a controller action with OutputCache attribute, looks like this:

[OutputCache(Duration = 14400)] // 4 hours
public ActionResult Index()
{
    var model = // fill out model

    return View(model);
}

So I cache the action for 4 hours. What I want to do is regardless of how long into these 4 hours, if it's after 10pm at night, I want to reset/clear the cache. Is this possible?


Solution

  • DateTime expireWeights = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59, 999); Cache.Insert("CacheItemName", list, null, expireWeights, System.Web.Caching.Cache.NoSlidingExpiration);
    

    You can set an absoluteExpiration time on the Cache object, which is a DateTime.

    You can also combine an absoluteExpiration with a SqlCacheDependency.

    Regarding the issue of it not pulling the new data when the cache expires: you can wire up a CacheItemRemovedCallback to receive notification of when it expires, and refresh the cache at that time.

    OR in model

    public class NoCache : 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);
        }
    }
    

    controller :-

    [NoCache]
    [Authorize]
    public ActionResult Home()
     {
         ////////...
    }
    

    you have to set the expiry by using below line code : DateTime.UtcNow.AddMinutes(1350). Or else (1350*60)--> duration and controller will have to go through your file every time the action call it

    [OutputCache(Duration = 81000, VaryByParam = "none")]
            public ActionResult Index()
            {
                //reset cache
                User u = new User();
                return Content(u.getCountryDetails());
                //send notification 
            }
    

    or You can add a Header to your HttpContext.Response in your controller

    HttpContext.Response.Headers.Add("refresh", "1350; url=" + Url.Action("Index"));
    

    there are many ways you can cache, its up to your comfortably.

    Hope helps you.