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:
- The websites use "InProc" as a session state mode by default. Therefore, the session state data is separated.
- 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:
- Use "SQLServer" as the session state mode and they decrypt and validate the session state data by using the same keys.
- 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
Notes
- 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:
<configuration>
<system.web>
<sessionState
mode="SQLServer"
sqlConnectionString="Data Source=localhost\sqlexpress;Integrated Security=True" />
</system.web>
</configuration>
Additionally, add these settings to make the web applications to decrypt and validate Session State data by using the same keys:
<configuration>
<system.web>
<machineKey
decryptionKey="EDCDA6DF458176504BBCC720A4E29348E252E652591179E2"
validationKey="CC482ED6B5D3569819B3C8F07AC3FA855B2FED7F0130F55D8405597C796457A2F5162D35C69B61F257DB5EFE6BC4F6CEBDD23A4118C4519F55185CB5EB3DFE61"/>
</system.web>
</configuration>
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 &&
!string.IsNullOrEmpty(context.Session.SessionID))
{
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:
<configuration>
<system.web>
<httpModules>
<add
name="SharedSessionModule"
type="CSASPNETShareSessionBetweenSubDomainsModule.SharedSessionModule, CSASPNETShareSessionBetweenSubDomainsModule, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
</system.web>
<appSettings>
<add key="ApplicationName" value="MySampleWebSite"/>
<add key="RootDomain" value="localhost"/>
</appSettings>
</configuration>
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
Languages
This code sample contains the following programming languages:
Language | Project Name |
---|---|
Visual C# | CSASPNETShareSessionBetweenSubDomains |
Visual Basic.NET | VBASPNETShareSessionBetweenSubDomains |