In this jumpstart, we are going to see how to use Cache and Distributed Cache tag helpers in ASP.Net Core. Cache tags are server side ASP.Net Core tags which are used to cache the contents on the server for better performance. There are various attributes available on the cache tags through which its behavior can be controlled.
To get started with ASP.Net Core 1.1, please refer to Upgrading from ASP.Net Core 1.0 to ASP.Net Core 1.1.
Cache tag can be used as shown below.
<cache expires-sliding="@TimeSpan.FromSeconds(10)" vary-by-query="test" priority="@Microsoft.Extensions.Caching.Memory.CacheItemPriority.Low"> @DateTime.Now </cache>
Cache tag supports following expiration options.
- expires-after: expires after specified time.
- expires-on: expires at specified time.
- expires-sliding: expires after specified time, but expiration time always ticks from last accessed time.
It also supports following vary-by options.
- vary-by: based on any arbitrary string value.
- vary-by-user: based on logged in user.
- vary-by-route: based on route data.
- vary-by-query: based on query string parameters.
- vary-by-cookie: based on cookie value.
Multiple vary-by options can be used on a single cache tag.
Cache priority can be set using priority attribute. This is useful when memory cache decides to release memory.
The main limitation for Cache tag is that it is In-Memory to a given server. This would result in different behavior when we have cluster of servers. To overcome this limitation we have distributed cache tag.
<distributed-cache name="DateCacheKey" expires-sliding="@TimeSpan.FromMinutes(10)" vary-by-query="test"> @DateTime.Now </distributed-cache>
All attributes are same between Cache and Distributed Cache tag except name. Name attribute is used by distributed cache tag to uniquely identify the cache portion.
We need to configure a distributed Cache, otherwise it is as good as In-Memory Cache. I have configured Redis Cache as detailed in this tutorial – JumpStart # 45 – Redis Cache based Session State in ASP.Net Core 1 MVC Application.
Run the application, we should see the Redis Cache entry as shown below.
That’s it for now, Happy Coding and Stay Tuned!!!