How to OutputCache an object based on the current date with VaryByCustom and GetVaryByCustomString

I have a long running script that needs to run once a day and I’d like to store the results of that script in cache for the rest of the day so only one user (or any automated http request) will incur the delay.

It took me a few mins to figure out the best cache the day for the rest of the day. I went back and forth between using ASP.NET Cache object directly and OutputCaching.

I ended up going with OutputCache because it is really simple and I don’t need to worry about locking, inserting, updaing like I would the Cache object.

I was going to use VaryByHeader=“Date”, but that would invalidate on the second, not the day like I need it to. So I ended up going with VaryByCustom.

OutputCache Attribute on Controller Action Method

  • Set VaryByCustom to Day
  • Set Duration = 86400, the number of seconds in a day. This is the max amount of time you want to cache. If the Custom VaryBy return value changes before the Duration expires then it will execute the controller action method again.
[OutputCache(VaryByCustom = "Day", Duration = 86400)]
public ActionResult Index()
{
    var report = new HealthReport();
    report.Load();
    return this.View(report);
}

Override GetVaryByCustomString in Global.asax.cs

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (string.Compare(custom, "Day", true) == 0)
    {
        return DateTime.Now.ToShortDateString();
    }
    return base.GetVaryByCustomString(context, custom);
}

Jon