Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

Sharing Session Across Applications

Rate me:
Please Sign up or sign in to vote.
3.86/5 (26 votes)
18 Jun 2008CPOL2 min read 285.2K   8.5K   63   76
A simple way to share session data accross web applications.

Introduction

This is intended to be a simple solution to sharing session data across applications. This implementation allows you to use the out of the box session providers that ship with ASP.NET without modifying any stored procedures, or creating custom session store providers.

Background

There was a large project going on at work, part of which involved splitting our one large website into smaller logical areas of functionality. This would provide us with more flexibility and manageability of our products. The only problem was, how would we share session data across applications?

Our current environment uses a SQL session store, so my first suggestion was to simply modify one of the stored procs to give all applications the same name, thus sharing session. That was quickly shot down by coworkers because they felt it would cause a support hole in the case that Microsoft would have to come in to troubleshoot anything related to session data. So, they decided to create custom session store providers. What they ended up doing is essentially creating exact code duplicates of the MS implementations for SQL and State Server session stores, and hacking in a few lines to change the application name (I am not sure how that is any better that changing a stored proc, but that was the decision).

As time came to actually implement this in our applications, I looked over the proof of concept, and found myself unable to actually use all that copied code simply to share session data. I just couldn't believe that there wasn't an easier way to solve this problem.

After spending about an hour searching the Internet, and not finding anything better, I decided to dig into the session manager code using Reflector to see if I could find anything.

Here's what I came up with...

Using the code

This shared session solution I came up with is fairly simple to use. Simply plug in the SharedSessionModule...

In the web.config of each application you would like to share session data for, add the following HTTP module:

XML
<httpModules>
   <add name="SharedSessionModule" type="Femiani.Web.Modules.SharedSessionModule, 
                                         Femiani.Web.Modules.SharedSessionModule"/>
</httpModules>

Then, set your application name:

XML
<appSettings>
    <add key="ApplicationName" value="SharedWeb"/>
</appSettings>

Points of interest

After digging around for a while, I found out where the session stores were getting the application name from. Then, using an HTTP module and some Reflection, I manually set the application name when the web application starts up.

C#
/// <summary>
/// SharedSessionModule class.
/// </summary>
/// <created date="5/31/2008" by="Peter Femiani"/>
public class SharedSessionModule : IHttpModule
{
    #region IHttpModule Members
    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/>
    /// that provides access to the methods,
    /// properties, and events common to all application objects within an ASP.NET
    /// application</param>
    /// <created date="5/31/2008" by="Peter Femiani"/>
    public void Init(HttpApplication context)
    {
        try
        {
            // Get the app name from config file...
            string appName = ConfigurationManager.AppSettings["ApplicationName"];
            if (!string.IsNullOrEmpty(appName))
            {
                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, appName);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }
    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that
    /// implements <see cref="T:System.Web.IHttpModule"/>.
    /// </summary>
    /// <created date="5/31/2008" by="Peter Femiani"/>
    public void Dispose()
    {
    }
    #endregion
}

And that's it! Pretty simple.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect People Media
United States United States
My name is Peter Femiani and I am a graduate of Arizona State University with a B.S. in Economics. I have been writing code since I was about 14.

Comments and Discussions

 
QuestionSame source code i am executed but not gettting the session value in second application Pin
devasish5224-Jan-21 18:42
devasish5224-Jan-21 18:42 
QuestionI am not getting the session id in second application please help Pin
Member 859179615-Aug-20 4:15
Member 859179615-Aug-20 4:15 
QuestionVS 2017 Framework 4.5.2 Pin
vj.negi0824-Feb-19 23:21
vj.negi0824-Feb-19 23:21 
Questionusing visual studoi 2012, cannot pass the session value. the session value is null Pin
Member 1332722827-Jul-17 16:51
Member 1332722827-Jul-17 16:51 
QuestionIt is not working for me Pin
Ajay_Saini10-Sep-15 1:35
Ajay_Saini10-Sep-15 1:35 
GeneralMy vote of 1 Pin
Member 92665974-Sep-14 0:59
Member 92665974-Sep-14 0:59 
AnswerAccessing shared session in Multiple MVC Web Applcations, Environment MVC 4, IIS7 Pin
Sandeep Negi29-Jun-14 23:21
Sandeep Negi29-Jun-14 23:21 
Questionme too except Pin
me_pollack28-Mar-14 10:44
me_pollack28-Mar-14 10:44 
GeneralMy vote of 1 Pin
Pratik Bhuva18-Feb-14 2:40
professionalPratik Bhuva18-Feb-14 2:40 
QuestionShare session Pin
cnnbs13-Feb-14 4:30
cnnbs13-Feb-14 4:30 
GeneralMy vote of 1 Pin
abdussalam14331-Jan-14 2:59
professionalabdussalam14331-Jan-14 2:59 
GeneralMy vote of 1 Pin
Mannava Siva Aditya2-May-13 20:23
Mannava Siva Aditya2-May-13 20:23 
QuestionSession is clear - No session data found Pin
Mannava Siva Aditya2-May-13 20:06
Mannava Siva Aditya2-May-13 20:06 
QuestionNo session data found. Pin
ashishishwar20-Mar-13 2:39
ashishishwar20-Mar-13 2:39 
QuestionI got it to work with FW 3.5 (SharePoint 2010) with a minor change Pin
emadm5-Oct-12 6:08
emadm5-Oct-12 6:08 
Questioniis 7.5 Pin
Dan_L3-Jul-12 4:10
Dan_L3-Jul-12 4:10 
QuestionSession not working in Second Application Pin
manojkumar.m.sierra22-Feb-12 19:39
manojkumar.m.sierra22-Feb-12 19:39 
BugBugfixes Pin
Sergiy Sakharov9-Feb-12 6:37
Sergiy Sakharov9-Feb-12 6:37 
GeneralRe: Bugfixes Pin
SashiRachakonda1-Mar-12 7:39
SashiRachakonda1-Mar-12 7:39 
GeneralRe: Bugfixes Pin
Member 859114921-Jun-12 2:06
Member 859114921-Jun-12 2:06 
GeneralRe: Bugfixes Pin
Dan_L1-Jul-12 22:59
Dan_L1-Jul-12 22:59 
QuestionRe: Bugfixes Pin
Sunil12331-Jul-13 16:51
Sunil12331-Jul-13 16:51 
QuestionCan't access session variable in second web application Pin
Member 393598417-Aug-11 20:17
Member 393598417-Aug-11 20:17 
GeneralFailed Pin
zohreh_av13-Apr-11 20:40
zohreh_av13-Apr-11 20:40 
GeneralWorking Except Redeployments require me to recycle the app pool Pin
test89214-Jan-11 10:52
test89214-Jan-11 10:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.