ASP.NET Core: On-Demand Cache Expiration with Custom Tag Helpers



Last updated: January 28th, 2024

Problem

Using ASP.NET Core's Cache Tag Helper can be useful when you have sections of code you want cached directly in your markup. The problem is that the expiration for this cache relies on time, headers or some other factor for expiration. It cannot be expired on demand when for example there is an update which should invalidate it.

Solution

It is possible to create a custom cache tag helper that has a key which can be used to expire the cache. By associating the cache with a key, the benefits of caching markup in the Razor views and on-demand cache expiration can be combined. This ensures both fresh data showing up when needed and having a long cache to prevent overwhelming a backend service like a database.

Cache Tag Helper

The cache tag helper allows rendering HTML, with a cache expiration time and key to be used for expiration elsewhere. Setting "output.TagName = null;" will prevent the output HTML from having your custom tag show up.

_ViewImports.cshtml

It's necessary to register the tag helper in the "_ViewImports.cshtml" file so it can be used in views.

Using Cache in View

By using the caching tag and its attributes, it's possible to do computationally expensive work and cache it. It can be cached until a certain time or removed when needed. Certain displays are easier to write out in C# when used directly in HTML, so this helps with that.

Expiring the Cache

By using the "IMemoryCache" (which needs to be setup in the Program.cs calling "AddMemoryCache()" on "WebApplicationBuilder"), it is possible to expire the cache on demand. The call to remove the cache can be done through a specific endpoint or by adding it after any call which modifies data, like when the database is updated.

Conclusion

By creating a custom cache helper, it's possible to build output one wants in a Razor view that can be cached and expire it when data changes elsewhere.


Comments

No Comments

Post Comment

Prove you are human 8 + 9 =

Tagged: ASP.NET, C Sharp


Join my email list!



ryan
About Me

With over 15 years in tech, I've excelled as a senior software engineer, specializing in ASP.NET, C#, SQL, Azure, and front-end technologies. I've led diverse projects across various sectors, from startups to global corporations, particularly during my decade in the San Francisco Bay Area.


Sign Up With SoftSys Hosting! (My host)