OutputCache / ResponseCache VaryByParam

ResponseCacheis a replacement for OutputCache; however, I would like to do caching on the server side, as well as on input parameters.

According to some answers here and here , I have to use IMemoryCacheor IDistributedCachedo this. I am particularly interested in caching on controllers, where the parameter is different, previously executed in asp.net 4 with OutputCacheand VaryByParamas follows:

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

How can I repeat this in asp.net core?

+5
source share
2 answers

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

, , :

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

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

+2

, ... , IMemoryCache, , ActionFilterAttribute .
( .Net core 2.1 Microsoft docs + my ):
1- services.AddMemoryCache(); ConfigureServices Startup.cs.
2- :

public class HomeController : Controller
{
  private IMemoryCache _cache;

  public HomeController(IMemoryCache memoryCache)
  {
      _cache = memoryCache;
  }

3- ( ) , :

public static class CacheKeys
{
  public static string SomeKey { get { return "someKey"; } }
  public static string AnotherKey { get { return "anotherKey"; } }
  ... list could be goes on based on your needs ...

enum:
public enum CacheKeys { someKey, anotherKey,...}
3- actionMethods, :
: _cache.TryGetValue(CacheKeys.SomeKey, out someValue)
, TryGetValue :

_cache.Set(CacheKeys.SomeKey, 
           newCachableValue, 
           new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(60)));  

.

0

Source: https://habr.com/ru/post/1626099/


All Articles