static void

ASP Caching

Generic session methods

HttpContext.Current is not available in WCF services - you can enable the asp pipeline with <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> (there's nothing equivalent in OperationContext, but you can use MemoryCache).

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.

<%@ OutputCache Duration="60" VaryByParam="none"%>

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;
}