How to share session state across subdomains


This article describes an All-In-One framework sample that is available for download. This code sample demonstrates a step-by-step guide that illustrates how to share Session State across Sub Domains.

You can download the sample package from the following icons.

Difficulty level

Download information

To download this code sample, click one of the following links:

Technical overview

Sometimes, developers want to host two or more ASP.NET websites that uses the same session state in multiple subdomains. Therefore, it is easier to make these websites to behavior as the same application and transfer the data across the websites. However, the following problems occur when the websites try to share the same session state:
  1. The websites use "InProc" as a session state mode by default. Therefore, the session state data is separated.
  2. The session state saves a token in Cookie to identify the current visiting, and Cookie cannot be shared across domains.
To use the same session state, use the following method to resolve above problems:
  1. Use "SQLServer" as the session state mode and they decrypt and validate the session state data by using the same keys.
  2. Save the session state token (session ID) with the root domain so that the token can be shared by all subdomains.

Sample Overview

This sample contains an HttpModule (also known as SharedSessionModule) assembly and two ASP.NET web application projects. The HttpModule assembly is used to behave the logic of sharing the session state. Two ASP.NET web application projects are used to demonstrate sharing session state. To share the session state across subdomains, follow these steps:

Step 1

Configure SQL Server to support the session state. Before you configure SQL Server to support the session state, you have to install SQL Server Express in your operating system.

Note SQL Server Express is normally shipped with Microsoft Visual Studio. To download SQL Server Express, visit the following Microsoft website:Then, run the following command in Console Window:
<system drive>:\Windows\Microsoft.NET\Framework\<.NETFrameworkversion>\aspnet_regsql.exe -S localhost\sqlexpress -E -ssadd
  • The <.NETFrameworkversion> is a placeholder for the version of the .NET Framework that is installed on your operating system.
  • If you do not add session state to SQL Server, you receive the following error message that is generated by the System.Data.SqlClient.SqlException class when you configure a website to use SQL Server mode session state:

    Invalid object name 'tempdb.dbo.ASPStateTempSessions'.

Step 2

Configure two ASP.NET web applications to use "SQLServer" as the session state mode.To do these, add these settings to the web.config configuration file for the web applications:
sqlConnectionString="Data Source=localhost\sqlexpress;Integrated Security=True" />
Additionally, add these settings to make the web applications to decrypt and validate Session State data by using the same keys:
Note If you host the web applications in Internet Information Services (IIS), run the Application Pool under an account that is able to login the database. Otherwise, you receive the following error message that is generated by the System.Data.SqlClient.SqlException:

Cannot open database 'ASPState' requested by the login. The login failed.

Step 3

Implement the logic in the HttpModule assembly. To do this, create a new class library that is named "CSASPNETShareSessionBetweenSubDomainsModule" and add a new class that is named "SharedSessionModule" to the project. At the beginning of the file, run the following code to import the necessary namespaces:
using System;
using System.Web;
using System.Reflection;
using System.Configuration;
Add two static variables to the class. The static variables are used to read settings from the web.config file. The application name represents a particular application when the application is running. The root domain is the domain that is shared by the ASP.NET applications.
protected static string applicationName = ConfigurationManager.AppSettings["ApplicationName"];
protected static string rootDomain = ConfigurationManager.AppSettings["RootDomain"];
Implement the Init() method, write code within the method to change the application name, and then  add an event handler to handle the PostRequestHandlerExecute event of current application at the end of the method.
FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime",
BindingFlags.Static | BindingFlags.NonPublic);
HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);
FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId",
BindingFlags.Instance | BindingFlags.NonPublic);
appNameInfo.SetValue(theRuntime, applicationName);

context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
In the PostRequestHandlerExecute event handler, all code is used to modify the ASP.NET_SessionId cookie which is used to store a session ID in the browser.
void context_PostRequestHandlerExecute(object sender, EventArgs e)
HttpApplication context = (HttpApplication)sender;
HttpCookie cookie = context.Response.Cookies["ASP.NET_SessionId"];

if (context.Session != null &&
cookie.Value = context.Session.SessionID;
if (rootDomain != "localhost")
cookie.Domain = rootDomain;
cookie.Path = "/";

Step 4

Configure two ASP.NET web applications to use the HttpModule assembly. To do this, add these settings to the web application projects to enable this HttpModule assembly:
type="CSASPNETShareSessionBetweenSubDomainsModule.SharedSessionModule, CSASPNETShareSessionBetweenSubDomainsModule, Version=, Culture=neutral"/>
<add key="ApplicationName" value="MySampleWebSite"/>
<add key="RootDomain" value="localhost"/>
Note If you run the applications with your own domains instead of localhost, you have to change the value of RootDomain after publishing.

Technology category

  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4.0


This code sample contains the following programming languages:
LanguageProject Name
Visual C#CSASPNETShareSessionBetweenSubDomains
Visual Basic.NETVBASPNETShareSessionBetweenSubDomains

More Information

What is All-In-One Code Framework?

All-In-One Code Framework shows most Microsoft development techniques by using code samples in different programming languages. Each example is carefully selected, composed, and documented to show one common code scenario. For more information about All-In-One Code Framework, visit the following Microsoft website:

How to find more All-In-One Code Framework samples

To find more All-In-One Code Framework samples, search for "kbcodefx" together with related keywords on the Microsoft support Web site. Or, visit the following Microsoft website:


For more information about the ASP.NET session state, visit the following MSDN website: For more information about ASP.NET SQL Server registration tool (Aspnet_regsql.exe), visit the following MSDN website: For more information about ASP.NET cookies, visit the following MSDN website:For more information about how to Create an ASP.NET HTTP module by using Visual C# .NET, visit the following MSDN website:
Rapid publishing disclaimer
Microsoft corporation and/or its respective suppliers make no representations about the suitability, reliability, or accuracy of the information and related graphics contained herein. All such information and related graphics are provided "as is" without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information and related graphics, including all implied warranties and conditions of merchantability, fitness for a particular purpose, workmanlike effort, title and non-infringement. You specifically agree that in no event shall Microsoft and/or its suppliers be liable for any direct, indirect, punitive, incidental, special, consequential damages or any damages whatsoever including, without limitation, damages for loss of use, data or profits, arising out of or in any way connected with the use of or inability to use the information and related graphics contained herein, whether based on contract, tort, negligence, strict liability or otherwise, even if Microsoft or any of its suppliers has been advised of the possibility of damages.


Article ID: 2527105 - Last Review: Apr 7, 2011 - Revision: 1