How to use the new Distributed Cache (SDK 1.7) for Asp.Net Session State
Until today AppFabric Distributed cache was used to host Azure web roles Asp.Net Session state. Unfortunately there were many problems with AppFabric Azure Distributed Cache:
- It was VERY expensive.
- It was not available in all Data Centers.
- It was slow.
Fortunately in the new SDK (1.7) we have the opportunity to use our resources (i.e. roles) to host the distributed cache cluster and get a free and performant cache.
So lets see how to use it to host asp.net session:
1. For each role that will donate some resource for the distributed cache cluster we should set the cache configuration. Open the new caching tab in the role configuration and enable the cache.
- Enable the cache
- Set the deployment policy (use existing roles or create dedicated ones)
- Provide a valid connection string to storage
- set the caching policy (sliding / fix expiration), TTL etc.
2. Now it is time to add code to the actual web role. First install the NuGet package by searching
for: "windowsazure.caching" and installing "Windows Azure Caching Preview".
The installation will add some configuration to web.config.
Set the name of the role (that hosts the cache) in the identifier property:
Now we have to set the session state provider by overriding the session provider configuration to:
<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
cacheName="default" useBlobMode="true" dataCacheClientName="default" />
The final step is of course to use the session in our application:
protected void btnClick_Click(object sender, EventArgs e)
if (Session["count"] == null)
// increment the counter
Session["count"] = (int)Session["count"] + 1;
lblCount.Text = Session["count"].ToString();