Here is what we use ( in a static class )
Be aware that Cache is global and NOT session based.
#region checkCache
/// <summary>
/// Will test for the requested value in the Session Cache.
/// </summary>
/// <typeparam name="T">Type of cached object</typeparam>
/// <param name="sKey">Key to search on</param>
/// <returns>T</returns>
public static T checkCache<T>(string sKey)
{
T returnValue = default(T);
if (HttpContext.Current != null)
{
object oValue = HttpContext.Current.Cache.Get(sKey);
if (oValue is T)
{
returnValue = (T)oValue;
}
}
return returnValue;
}
#endregion
#region cacheItem
/// <summary>
/// Cache items to the session chache for a set number of
minutes.
/// </summary>
/// <param name="sKey"></param>
/// <param name="oItem"></param>
/// <param name="cacheMinutes"></param>
public static void cacheItem(string sKey, object oItem, int
cacheMinutes)
{
if (HttpContext.Current != null && oItem != null)
{
Cache cache = HttpContext.Current.Cache;
object oExistingItem = cache.Get(sKey);
// If the item is already cached
if (oExistingItem != null)
{
cache.Remove(sKey);
}
cache.Add(sKey, oItem, null,
DateTime.Now.AddMinutes(cacheMinutes), Cache.NoSlidingExpiration,
CacheItemPriority.Normal, null);
}
}
#endregion
#region expireCacheItem
/// <summary>
/// Removes an item from the Cache.
/// </summary>
/// <param name="sKey"></param>
public static void expireCacheItem(string sKey)
{
if (HttpContext.Current != null)
{
HttpContext.Current.Cache.Remove(sKey);
}
}
#endregion