Tutorial - Implement Cache with the Help of User Wise in Dot Net Development

Aegis Soft Tech team of asp.net development has just worked on MVC project that requires storing of some common values inside server object. When the user login, the common object will get stored in server object. How it will happen? In this tutorial, you will learn to achieve this by using three things- server states, session state, and cache. Let’s learn more about these things before coming to the coding part.

Recently one of our MVC project required to store some common values in server object.  So, once user login then common object will be stored in server object. To achieve this scenario we can use server states 1) Session state 2) Cache.

Following is the difference between session and cache in MVC application.

  • One important difference is, that items in the cache can expire (will be removed from cache) after a specified amount of time
  • ASP.NET can also remove items from cache when the amount of available memory gets small.
  • Session is per user/session while cache is per application.
  • Another important difference, Session State will be blocked if concurrent async Ajax requests are executed, it will effect performance.
  • Main benefit of the cache in Asp.Net application we can set expiry time so it will remove automatically from the server memory.

The conclusion of above difference is if you have small data to store in server you can use Session but if you want to store large amount of data in server state then session will effect performance of your application. 


Main requirement of our project is to store large amount of data in server and that data will be stored and retrieved by logged in user. So we have implemented a static class to store and retrieve data from cache. 


Steps to create a static class to add, remove and get value from/to cache in MVC or Asp.net application.

  • Create a static class like name is “CacheHelper.cs”
  • Create a static property to retrieve logged in user name
 Private static LoggedInUserName { get { return “Logged in UserName” } }  

  • Create a following static methods.
     public static bool Add(string key, dynamic value)  
     {  
       bool r = false;  
       if (!string.IsNullOrEmpty(this.LoggedInUserName))  
       {  
         key = this.LoggedInUserName + "$_$" + key;  
         HttpContext.Current.Cache.Insert(key, value, null, DateTime.UtcNow.AddMinutes(30), System.Web.Caching.Cache.NoSlidingExpiration);  
       }  
       return r;  
     }  
 public static bool Add(string key, dynamic value, double expireMinutes)  
     {  
       bool r = false;  
        if (!string.IsNullOrEmpty(this.LoggedInUserName))  
       {  
         key = this. LoggedInUserName + "$_$" + key;  
         HttpContext.Current.Cache.Insert(key, value, null, DateTime.UtcNow.AddMinutes(expireMinutes), System.Web.Caching.Cache.NoSlidingExpiration);  
       }  
       return r;  
     }  
 public static dynamic Get(string key)  
     {  
       dynamic r = null;  
       if (!string.IsNullOrEmpty(this.LoggedInUserName))  
       {  
         key = this. LoggedInUserName + "$_$" + key;  
         if (isExists(key))  
           r = System.Web.HttpContext.Current.Cache[key];  
       }  
       return r;  
     }  
 private static bool isExists(string key)  
 {  
 return System.Web.HttpContext.Current.Cache[key] != null;  
  }  
 public static void RemoveAllCache()  
     {  
 if (!string.IsNullOrEmpty(this.LoggedInUserName))  
       {  
         var userKey = this. LoggedInUserName + "$_$";  
         var keysToClear = (from System.Collections.DictionaryEntry dict in System.Web.HttpContext.Current.Cache  
                   let key = dict.Key.ToString()  
                   where key.StartsWith(userKey)  
                   select key).ToList();  
         foreach (var key in keysToClear)  
         {  
           System.Web.HttpContext.Current.Cache.Remove(key);  
         }  
       }  
     }  
 public static void Remove(string key)  
     {  
 if (!string.IsNullOrEmpty(this.LoggedInUserName))  
       {  
         key = this. LoggedInUserName + "$_$" + key;  
         if (isExists(key))  
           System.Web.HttpContext.Current.Cache.Remove(key);  
       }  
     }  


How to use above method in your application

1) Add method.


 CacheHelper.Add(“CountryList”, values);  

CountryList = is the identity to store data in cache.
Values = is the object of country list.
The default expiration time of cache value is 10 minutes.

 CacheHelper.Add(“CountryList”, values, 20);  

CountryList = is the identity to store data in cache.
Values = is the object of country list.
Expiration Time = is the minutes after that cache value automatic expire in the memory

2) Get method.

 Var countryList = CacheHelper.Get(“CountryList”);  

CountryList = is the identity to store data in cache.
You can retrieve collection of country list in the output variable.

3) Check cache value is exists or not

 bool isExists = bool isExists(“CountryList”)  

CountryList = is the identity to store data in cache.
This method is used to check whether cache is exists or not in memory.

4) RemoveAllCache.

 RemoveAllCache()  

This methods is used to remove all the cache value from the memory of logged in user.

5) Remove

 Remove(“CountryList”)  

Above method remove a particular object from the memory.

Asp.net MVC development team posted this article to help people in implementing cache by user wise. You can ask any of the point that you did not get from experts in your comments. They will get back to you within a day.