Caching in Asp.net Core Example

Caching is one of most important features we often use in asp.net application development, here we learn how to do Caching in Asp.net Core application, how caching can improve application performance, learn different type of caching in asp.net core.

We will be learning using IMemoryCache _cache; for caching object.

How to use caching in ASP.Net Core

ASP.Net Core framework provides different types of caching support like in-memory caching, response caching and distributed caching.

The core concept of caching remain same as earlier asp.net MVC caching, however, the caching framework implementation has been improved a lot in asp.net core caching.

Cache in-memory in ASP.NET Core

In-memory caching is the technique of storing complex data, which are common in nature and not going to change very frequently, data like country list, currency list, daily forecast etc.

This caching can really improve application performance by fetching data faster from cache server without connecting and re-generating data from database. Here in example below we learn how to use in-memory caching.

Like earlier ASP.Net version, in Asp.net Core we don't have any Cache object. here caching to be implemented with the help of IMemoryCache object.

public interface IMemoryCache : IDisposable
{
	bool TryGetValue(object key, out object value);
	ICacheEntry CreateEntry(object key);
	void Remove(object key);
}	

Now you may wonder why there are only three methods in IMemoryCache definition! What about other methods like Get, Set, TryGetValue etc, all those methods are written in extensions class.

IMemoryCache is the service that provides all required methods to store and retrieve objects from cache, to use the service we need to register the service in ConfigureServices method of startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

Now in controller we have to create the instance of IMemoryCache service using dependency injection through constructor.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
namespace WebTrainingRoom.Controllers
{
    public class histController : Controller
    {
        private IMemoryCache _cache;
        public histController(IMemoryCache cache)
        {
            _cache = cache;
        }
        
        public IActionResult Index()
        {
             _cache.GetOrCreate<string>("myKey",
                cacheEntry => {
                    return DateTime.Now.ToString();
                });
            return View();
        }
    }
} 

Instead of using "GetOrCreate" method like in above example, we can use the async method called "GetOrCreateAsync", we can get data asynchronously form cache like example below.

public async Task<List<Country>> GetCountryList()
{
	var countries = await
	_cache.GetOrCreateAsync(countryKey, entry =>
	{
	entry.SlidingExpiration = TimeSpan.FromSeconds(1000);
	return Task.Run(GetCountryCache);
	});
	return countries;
}

private async Task<List<Country>> GetCountryCache()
{
	List<Country> countries = await CommonDTO.GetCountryListAsync();
	return countries.ToList();
}

Notice, we have set cache SlidingExpiration property value to 1000 seconds, that indicates if the cache entry not being accessed for 1000 seconds, then the entry will be removed from cache server.

Here is example of how to get and set value in Cache object.

In this example we are trying to retrieve the country list from cache object, at the same time if the country list not available in cache, then just fetch from original location(like database, xml file etc) and set it in cache, so next time we will be able to retrieve from cache.

List<Country> countries;

if (_cache.TryGetValue(countryKey, out countries))
{
	ViewBag.Countries = countries;
}
else
{
	countries = CommonDTO.GetCountryList();
	_cache.Set(countryKey, countries);
}

Cache Tag Helper in ASP.NET Core

In asp.net core we have cache tag, which internally uses in-memory caching, cache tag (<cache></cache>) is very easy to use in razor view, any content inside that cache tag will be stored in cache server.

We can specify many additional attributes like expires-on, expires-after, expires-sliding, vary-by-header, vary-by-query etc.

Cache tag helper makes partial caching very easy , now we can cache any part of the page cacheable with the help of Cache tag (<cache></cache>)

We can disable cache tag by setting it’s attribute value to false, true by default, like <cache enabled="false"></cache>

<cache>
    Present Time inside Cache Tag: @DateTime.Now
</cache>

  • expires-on: set an absolute expiration date for the cached content.

    <cache expires-on="@new DateTime(2050,10,10)">
        Current Time: @DateTime.Now , expires-on example
    </cache>
    
  • expires-after: set the expiration time in seconds

    <cache expires-after="@TimeSpan.FromSeconds(240)">
        Current Time : @DateTime.Now, expires-after example
    </cache>
    
Response caching in ASP.NET Core

Response caching is a technique of storing page in cache server location for some duration, so instead of fetching from server every time we can fetch the page from server, that really help page loading faster, Response caching is controlled by headers information.

To use response caching you must add UseResponseCaching method to IApplicationBuilder instance in Configure method of startup.cs file.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseResponseCaching();
}

Response Cache attribute can be applied at controller level as well as view level, Response Cache attribute has many optional parameter like Duration, Header etc.

[ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
public class histController : Controller
{
    [ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
    public IActionResult Index()
    {
		 
        return View();
    }
}   

asp.net core also provide distributed caching, where we store the object in a different server, below are the few options for implementing distributed caching.

  • We can store data on Redis cloud, For a Redis distributed cache, use Microsoft.Extensions.Caching.StackExchangeRedis from Nuget package manager.
  • Store data in SQL server. For SQL Server, use Microsoft.Extensions.Caching.SqlServer The Distributed SQL Server Cache implementation can be done from Nuget manager.
  • For the NCache distributed cache, use NCache.Microsoft.Extensions.Caching.OpenSource NCache is an open source in-memory distributed cache developed natively in .NET and .NET Core

Asp.Net Core C# Examples | Join Asp.Net MVC Course