8

I'm trying to reproduce something I found here for a previous version of ASP.NET.

Basically, I want to be able to disable cache so my client's look to the server for information at all times. I've added an HTML meta tag for this, but for client's that already have this information, I wanted to experiment with handling cache policy on the back-end.

The post mentions doing this to set a cache policy as an action filter.

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

However, HttpContext doesn't appear to have a Response.Cache in ASP.NET Core. Is there an alternative way of doing this?

Thanks!

Community
  • 1
  • 1
jackmusick
  • 151
  • 1
  • 6

2 Answers2

19

You could directly set the corresponding response headers to the desired values:

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
        filterContext.HttpContext.Response.Headers["Expires"] = "-1";
        filterContext.HttpContext.Response.Headers["Pragma"] = "no-cache";

        base.OnResultExecuting(filterContext);
    }
}
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
0

You can control it with build-on attribute:

[ResponseCache (NoStore = true, Location = ResponseCacheLocation.None)]
mk_yo
  • 644
  • 1
  • 9
  • 33