Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to share session state across subdomains


INTRODUCTION

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:

Download SQL Server Express

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

↑ Back to the top


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:

↑ Back to the top


References

For more information about the ASP.NET session state, visit the following MSDN website:

General information about the ASP.NET session state

For more information about ASP.NET SQL Server registration tool (Aspnet_regsql.exe), visit the following MSDN website:

General information about ASP.NET SQL Server registration tool

For more information about ASP.NET cookies, visit the following MSDN website:

General information about ASP.NET cookies

For more information about how to Create an ASP.NET HTTP module by using Visual C# .NET, visit the following MSDN website:

How to Create an ASP.NET HTTP module by using Visual C# .NET

↑ Back to the top


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.

↑ Back to the top


Keywords: kbcodefx, kbinfo, kbrapidpub, kbnomt, kbsurveynew, atdownload, kb

↑ Back to the top

Article Info
Article ID : 2527105
Revision : 2
Created on : 11/1/2018
Published on : 11/1/2018
Exists online : False
Views : 1441