Use Cache and Distributed Cache Tag Helpers in ASP.NET Core

Web developers often look for opportunities to boost the performance of their web applications. ASP.NET Core provides server side caching in the form of in-memory and distributed cache implementation. Moreover, it offers two Tag Helpers to implement caching HTML content of razor views or razor pages - Cache and Distributed Cache. To that end this article discusses these Tag Helpers in brief.

Cache Tag Helper

The Cache Tag Helper allows you cache HTML content of a razor view of a razor page. In its simplest form the <cache> Tag Helper can be used as follows:

    <h3>This content is cached : @DateTime.Now</h3>

The above markup caches the timestamp for 20 minutes (default value). You can place all the content to be cached inside the <cache> and </cache> tag. The content could be plain HTML markup or razor markup and code.

The <cache> Tag Helper has many attributes that can be used to configure the caching behavior. Some commonly used attributes are illustrated below.

<cache expires-after="@TimeSpan.FromMinutes(30)">
    <h3>This content is cached : @DateTime.Now</h3>

The expires-after property specifies a TImeSpan (30 minutes in this example) after which the cached output is removed from the server enabling for the new cached version to be created.

<cache expires-on="@DateTime.Now.AddMinutes(30)">
    <h3>This content is cached : @DateTime.Now</h3>

The expires-on takes a DateTimeOffset and expires the cached content as per the resultant date and time value. In the above case the content will be cached till the DateTime value is same as 30 minutes from now. This option is similar to the earlier one but uses an explicit DateTime value rather than a TimeSpan value.

<cache expires-sliding="@TimeSpan.FromSeconds(30)">
    <h3>This content is cached : @DateTime.Now</h3>

The explires-sliding is a TimeSpan after which the cached content expires if not accessed. Notice the difference between expires-after and expires-sliding. The expires-after property will expire the content whether the page is being accessed or not. On the other hand expires-sliding is a timeout value and will renew the expiration time if the page is accessed within that time window.

Distributed Cache Tag Helper

The Cache Tag Helper just discussed uses memory of the server to store the cached content. It has the same set of attributes as discussed earlier. In addition you need to specify the name attribute. The name attribute is used as a key while storing the cache. The Cache Tag Helper that assigns a cache key automatically for you and hence doesn't need name attribute.

The Distributed Cache Tag Helper uses a separate storage such as a SQL Server ot Redis. To use the Distributed Cache Helper you need to enable the distributed caching for your web application. In this example we will use a SQL Server to store the cache.

First of all add NuGet package for Microsoft.Extensions.Caching.SqlServer and then issue this command at the Visual Studio Developer Command Prompt.

dotnet sql-cache create 
"Data Source=.;Initial Catalog=Northwind;Integrated Security=True;" 
dbo MySQLCache

In the above "create" command you specify the database connection string of the database acting as the cache item data store. The connection string is followed by table schema and a table name of your choice. A successful run of the above command will create MySQLCache table inside Northwind database. The MySQLCache table will be used to store the cache.

Now, open the Startup class and go to the ConfigureServuces() method. Then write the following code there:

services.AddDistributedSqlServerCache(options =>
        options.ConnectionString = @"Data Source=.;
Initial Catalog=Northwind;Integrated Security=True;";
        options.SchemaName = "dbo";
        options.TableName = "MySQLCache";

The AddDistributedSqlServerCache() method registers the distributed cache service with the DI framework. While adding the SQL Server distributed cache a few options are configured. The database connection string, table schema and table name are specified as the configuration information.

Now you can use the <distributed-cache> Tag Helper in a view file or a razor page.

<distributed-cache name="mydistcache" 
    <h3>This content is cached : @DateTime.Now</h3>

If you run the above page you will see an entry getting added to the MySQLCache table.

To read more about Cache Tag Helper and Distributed Cache Tag Helper go here and here.

That's it for now! Keep coding!!

Bipin Joshi is a software consultant, trainer, author, yoga mentor, and spiritual guide having 24+ years of experience in software development, consulting, and training. He conducts instructor-led online training courses in ASP.NET Core, ASP.NET MVC, and Design Patterns for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn

Posted On : 08 April 2019

Tags : ASP.NET ASP.NET Core SQL Server MVC C#

Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.


Receive Weekly Updates