Problem

How to use Distributed Cache Tag Helper in ASP.NET Core MVC.

Solution

In an empty project, update Startup class to add services and middleware for MVC and Distributed Cache.

Add a Controller.

Add a _ViewImports.cshtml page in Views folder. Add the directive to import tag helpers.

Add a Razor page (Index.cshtml).

Run the sample, keep refreshing. You’ll notice that the cached time doesn’t refresh (until cache expires).


Discussion

Cache and Distributed Cache Tag Helper helps improve the performance of your application by caching view’s content, either in-memory or in a distributed cache (e.g. Redis).

Distributed Cache Tag Helper uses IDistributedCache to store the content in a distributed cache. To learn more about distributed caching, please refer to an earlier post here.

Attributes

Cache Tag Helper has the following attributes,

Source Code

GitHub