Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutputCache / ResponseCache VaryByParam

ResponseCache is somewhat a replacement for OutputCache; however, I would like to do server side caching as well as per parameter input.

According to some answers here and here, I should be using IMemoryCache or IDistributedCache to do this. I'm particularly interested in caching on controllers where the parameter is different, previously done in asp.net 4 with OutputCache and VaryByParam like so:

[OutputCache(CacheProfile = "Medium", VaryByParam = "id", Location = OutputCacheLocation.Server)]
public ActionResult Index(long id) 
{ 
    ///...
}

How would I go about replicating this in asp.net core?

like image 922
Nick De Beer Avatar asked Jan 27 '16 03:01

Nick De Beer


2 Answers

If you want to change the cache by all request query parameters in all requests in the controller:

[ResponseCache(Duration = 20, VaryByQueryKeys = new[] { "*" })]
public class ActiveSectionController : ControllerBase
{
   //...
}
like image 75
Sergey Avatar answered Sep 28 '22 10:09

Sergey


First be sure you are using ASP.NET Core 1.1 or higher.

Then use a code similar to this on your controller method:

[ResponseCache(Duration = 300, VaryByQueryKeys = new string[] { "date_ref" } )]
public IActionResult Quality(DateTime date_ref)

Source: https://docs.microsoft.com/en-us/aspnet/core/performance/caching/middleware

like image 20
Raffaello Damgaard - MCSD Avatar answered Sep 28 '22 08:09

Raffaello Damgaard - MCSD