ASP Caching
State Servers
I strongly recommend using the 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