ASP Caching
For Core, ignore everything below this (although System.Runtime.Caching still exists).
- install Microsoft.Extensions.Caching.Memory
- in your startup .Services.AddMemoryCache()
- In classes, get IMemoryCache via ctor injection
- Session (HttpSessionState) - per user cache
- Application (HttpApplicationState - global cache (all users). DOES NOT EXPIRE.
- Cache (on HttpRuntime and HttpContext.Current) - Web.Caching.Cache) - global cache (all users). CAN SET EXPIRY.
- ObjectCache (.Net 4, MemoryCache, reference System.Runtime.Caching.dll) -
global cache for asp/non-asp (no out-of-the-box Sql/State providers). CAN SET EXPIRY as absolute datetime or CachePolicy. - Page Output caching - stores rendered HTML and/or uses HTTP caching
State Servers
Use Session State service on development machines, because it reminds you to only store ISerializable objects.
<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false" timeout="20"/>
The command to setup the SQLServer session provider for a webfarm is:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Aspnet_regsql.exe -S ServerName -U username -P password -ssadd
Append -sstype p to use database "ASPState" instead of tempdb. MSDN
Output caching
See Quickstarts, MSDN concept - MSDN OutputCache.
- You MUST have Duration and either VaryByParam (QueryString) or VaryByControl
- For VaryByCustom you must override GetVaryByCustomString
- Configure on page, user control or web.config cache profiles. If you reference cached user controls in code-behind, check for null.
- In 2.0 you also have the "anti-caching" Substitution control.
No caching:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
Cache API
HttpRuntime.Cache==HttpContext.Current.Cache but works (slowly) when HttpContext.Current is null so you can use it in console apps/unit tests.
Cache Cache = HttpRuntime.Cache;
string filepath = HttpContext.Current.Server.MapPath(@"\\serverX\data.xml");
Cache["Key"] = o; //simple "non-expiring"
//file dependency (see also AggregateCacheDependency)
Cache.Insert("Key", o, new CacheDependency(filepath));
//expire at midnight
Cache.Insert("Key", o, null, DateTime.Now.AddDays(1).Date, TimeSpan.Zero);
//sliding expiration for minimum 30 minutes
Cache.Insert("Key", o, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
//Cache.Add == Cache.Insert, but Add will not update if it already exists (silently, no exception).
//Cache.Insert has overloads, Cache.Add does not
Cache clearing
There's no Clear method.
public static void ClearCache()
{
var cacheKeys = new List<string>();
var enumerator = HttpRuntime.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
cacheKeys.Add(enumerator.Key.ToString());
}
foreach (var key in cacheKeys)
{
HttpRuntime.Cache.Remove(key);
}
}
.Net 4 MemoryCache
Very useful for unit testing. Can be extended for database-backed cache, but it can't use ASP.Net's Session/Application providers (state server, SqlServer).
public static object GetCache<T>(string key, Func<T> load)
where T : class
{
//get the static "default" cache.
ObjectCache cache = MemoryCache.Default;
//you can't store null in the cache
var value = cache[key] as T;
if (value == null)
{
value = load();
cache[key] = value;
// ...or...
//var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(5) };
//cache.Add(key, value, policy);
}
return value;
}