Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 760
jackmusick Avatar asked Jan 17 '17 15:01

jackmusick


People also ask

What is HttpContext in .NET Core?

HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.

What is response caching in .NET Core?

Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is controlled by headers that specify how you want client, proxy, and middleware to cache responses.

How do I get HttpContext in .NET Core?

In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.


1 Answers

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);
    }
}
like image 67
Darin Dimitrov Avatar answered Oct 16 '22 16:10

Darin Dimitrov