简体   繁体   中英

HttpContext.Response.Cache equivalent in .NET Core?

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!

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);
    }
}

您可以使用 build-on 属性控制它:

[ResponseCache (NoStore = true, Location = ResponseCacheLocation.None)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM