Learning never exhausts the mind
Home >  Coding > C# ASP.Net MVC > Simple ASP.Net Caching in C#

Published 3rd April 2013 by

A short ASP.NET caching snippet written in C# for ASP.Net or MVC which stores data in the cache reducing page generation times.

This ASP.Net caching technique is useful for scenarios where data is retrieved from a database or third party API and does not have to be updated in real time.

In the example below, there is a custom data type called MyDataType, although any .Net class can be used here.

Firstly, a call is made to get the object data from the cache location "key". If the data is not found the function returns null, so by checking if the result is null we know if the data was found in the cache or not. If the data is not found, we simply go ahead and get the data from the database or API as normal. The data is then inserted into the cache for next time.

The example below has two calls to HttpRuntime.Cache.Insert - you only need to use one of them. The two examples given are for storing the data indefinitely and for storing the data for a specified time.

If the data is found in the cache then it can be checked to make sure that it is the correct data type (nothing has overridden the data with something else for example) then it is cast back to the original data type.

MyDataType dataToGet = new MyDataType();

object cachedObjectData = HttpRuntime.Cache.Get("key");
if (cachedObjectData == null)
    // Data was not found in the cache so get the data from database or external API
    dataToGet = GetMyData();

    // Put the data into the cache (make sure the key is the same as above
    // Data will remain in the cache until the application is restarted or the cache cleared
    HttpRuntime.Cache.Insert("key", dataToGet);

    // If you want to force a refresh of the data periodically, use an expiration
    // This will cause the data to be invalid after one hour and will be got from source again.
    // You can use any of the TimeSpan methods to keep data for a few seconds to days or years.
    HttpRuntime.Cache.Insert("key", dataToGet, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1));
    // Data was found in the cache, now cast to original data type
    // You should do some checking that the cached data is the correct data type to prevent invalid cast exception
    dataToGet = (MyDataType)cachedObjectData;

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.