Click here to Skip to main content
Click here to Skip to main content

Sharing Session Across Applications

By , 18 Jun 2008
Rate this:
Please Sign up or sign in to vote.

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:

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

Then, set your application name:

<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.

/// <span class="code-SummaryComment"><summary></span>
/// SharedSessionModule class.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><created date="5/31/2008" by="Peter Femiani"/></span>
public class SharedSessionModule : IHttpModule
{
    #region IHttpModule Members
    /// <span class="code-SummaryComment"><summary></span>
    /// Initializes a module and prepares it to handle requests.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="context">An <see cref="T:System.Web.HttpApplication"/></span>
    /// that provides access to the methods,
    /// properties, and events common to all application objects within an ASP.NET
    /// application<span class="code-SummaryComment"></param></span>
    /// <span class="code-SummaryComment"><created date="5/31/2008" by="Peter Femiani"/></span>
    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);
        }
    }
    /// <span class="code-SummaryComment"><summary></span>
    /// Disposes of the resources (other than memory) used by the module that
    /// implements <span class="code-SummaryComment"><see cref="T:System.Web.IHttpModule"/>.</span>
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><created date="5/31/2008" by="Peter Femiani"/></span>
    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)

About the Author

pfemiani
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

 
Questionme too except Pinmemberme_pollack28-Mar-14 10:44 
GeneralMy vote of 1 PinprofessionalPratik Bhuva18-Feb-14 2:40 
QuestionShare session Pinmembercnnbs13-Feb-14 4:30 
GeneralMy vote of 1 Pinprofessionalabdussalam14331-Jan-14 2:59 
GeneralMy vote of 1 PinmemberMannava Siva Aditya2-May-13 20:23 
QuestionSession is clear - No session data found PinmemberMannava Siva Aditya2-May-13 20:06 
QuestionNo session data found. Pinmemberashishishwar20-Mar-13 2:39 
QuestionI got it to work with FW 3.5 (SharePoint 2010) with a minor change Pinmemberemadm5-Oct-12 6:08 
Questioniis 7.5 PinmemberMember 78957013-Jul-12 4:10 
QuestionSession not working in Second Application Pinmembermanojkumar.m.sierra22-Feb-12 19:39 
BugBugfixes PinmemberSergiy Sakharov9-Feb-12 6:37 
GeneralRe: Bugfixes Pinmemberlevel3comm1-Mar-12 7:39 
GeneralRe: Bugfixes PinmemberMember 859114921-Jun-12 2:06 
I know that this is a bit old, but could be the fix I need. Could you please elaborate on the changes you made? Specifically that of your first point?
GeneralRe: Bugfixes PinmemberMember 78957011-Jul-12 22:59 
QuestionRe: Bugfixes PinmemberSunil12331-Jul-13 16:51 
QuestionCan't access session variable in second web application PinmemberMember 393598417-Aug-11 20:17 
GeneralFailed Pinmemberzohreh_av13-Apr-11 20:40 
GeneralWorking Except Redeployments require me to recycle the app pool Pinmembertest89214-Jan-11 10:52 
GeneralThis is not working Pinmemberaesalan11-Oct-10 3:10 
GeneralThis is not working PinmemberMember 945980925-Sep-12 19:30 
GeneralNot able to retreive the session in the second web application Pinmembertarungogia4-Oct-10 3:33 
QuestionIn IIS7 PinmemberRajan Devaraj2-Jun-10 7:25 
AnswerRe: In IIS7 Pinmemberavalon12311-Aug-11 4:49 
GeneralRe: In IIS7 PinmemberMember 78957011-Jul-12 23:07 
GeneralNew approach - with Distributed Cache PinmemberKrenning16-Jan-10 22:53 
AnswerProblem Solved - IIS 7 modification..... PinmemberKrenning3-Jan-10 3:19 
GeneralRe: Problem Solved - IIS 7 modification..... Pinmemberkarotijam23-Feb-10 6:04 
GeneralNot working for me Pinmembermbowles20117-Sep-09 3:16 
AnswerRe: Not working for me PinmemberKrenning3-Jan-10 3:00 
GeneralMy vote of 1 PinmemberSantosh G17-May-09 21:06 
GeneralRe: My vote of 1 PinmemberKrenning3-Jan-10 2:54 
GeneralElegant solution but doesn't work for me PinmemberSphengle23-Apr-09 7:13 
GeneralThanks Pinmembershahzadsb14-Apr-09 11:04 
GeneralAlways new session accross domains Pinmemberhcakir14-Mar-09 15:04 
GeneralNot working with Response.Redirect Pinmemberxueco23-Jan-09 6:40 
GeneralRe: Not working with Response.Redirect Pinmemberxueco26-Jan-09 0:08 
QuestionWhat environment did you use? It did not work IIS 7.0, VS 2008 Pinmemberdetails@insidespirit.com1-Jan-09 15:43 
QuestionDidn't work PinmemberCladdha16-Dec-08 5:01 
AnswerRe: Didn't work PinmemberCagdas Basaraner15-Jun-10 20:37 
GeneralAsp.Net 1.1 PinmemberShayis30-Nov-08 22:22 
GeneralConfiguration Error [modified] Pinmember-rain-26-Nov-08 23:07 
Questionsharing session data accross servers? PinmemberValens_Lu19-Nov-08 18:35 
Generalimpressively easy :-) Pinmembercribe8-Oct-08 8:52 
GeneralNo Funciona PinmemberJoshue24-Sep-08 7:46 
GeneralNeed urgent help Pinmembermamtamastek24-Sep-08 3:33 
GeneralSharing session between .net 1.1 and 2.0 Pinmemberwijayae26-Aug-08 23:20 
Generalsharing session data accross servers PinmemberMember 277935621-Aug-08 19:59 
GeneralInProc and StateServer Modes PinmemberPavi Sivya20-Aug-08 6:19 
GeneralRe: InProc and StateServer Modes Pinmemberissac@limosys.com22-Jan-10 6:45 
QuestionDoes this work in 2.0 and vb PinmemberAsha100917-Jul-08 10:33 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 19 Jun 2008
Article Copyright 2008 by pfemiani
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid