Click here to Skip to main content
Licence CPOL
First Posted 18 Jun 2008
Views 90,365
Downloads 1,759
Bookmarked 53 times

Sharing Session Across Applications

By | 18 Jun 2008 | Article
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:

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

/// <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)

About the Author

pfemiani

Architect
People Media
United States United States

Member

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralNot working with Response.Redirect Pinmemberxueco6:40 23 Jan '09  
GeneralRe: Not working with Response.Redirect Pinmemberxueco0:08 26 Jan '09  
QuestionWhat environment did you use? It did not work IIS 7.0, VS 2008 Pinmemberdetails@insidespirit.com15:43 1 Jan '09  
QuestionDidn't work PinmemberCladdha5:01 16 Dec '08  
AnswerRe: Didn't work PinmemberCagdas Basaraner20:37 15 Jun '10  
GeneralAsp.Net 1.1 PinmemberShayis22:22 30 Nov '08  
GeneralConfiguration Error [modified] Pinmember-rain-23:07 26 Nov '08  
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
 
Parser Error Message: Could not load type 'Femiani.Web.Modules.SharedSessionModule'.
 
i dont know whats wrong... help
 
and when i run your example.. there is no session found....
 
modified on Thursday, November 27, 2008 5:14 AM

Questionsharing session data accross servers? PinmemberValens_Lu18:35 19 Nov '08  
Generalimpressively easy :-) Pinmembercribe8:52 8 Oct '08  
GeneralNo Funciona PinmemberJoshue7:46 24 Sep '08  
GeneralNeed urgent help Pinmembermamtamastek3:33 24 Sep '08  
GeneralSharing session between .net 1.1 and 2.0 Pinmemberwijayae23:20 26 Aug '08  
Generalsharing session data accross servers PinmemberMember 277935619:59 21 Aug '08  
GeneralInProc and StateServer Modes PinmemberPavi Sivya6:19 20 Aug '08  
GeneralRe: InProc and StateServer Modes Pinmemberissac@limosys.com6:45 22 Jan '10  
GeneralSome issues [modified] Pinmembermrcraft15:45 14 Aug '08  
GeneralRe: Some issues Pinmemberfrankbret210:11 10 Dec '08  
GeneralNot working for ASP State Server PinmemberEdwinY20:32 11 Aug '08  
GeneralRe: Not working for ASP State Server Pinmemberpfemiani5:06 12 Aug '08  
GeneralRe: Not working for ASP State Server Pinmemberlevel3comm14:14 29 Feb '12  
GeneralI have an error in my web.config [modified] PinmemberMember 242834219:48 4 Aug '08  
AnswerRe: I have an error in my web.config PinmemberKrenning3:02 3 Jan '10  
QuestionDoes this work in 2.0 and vb PinmemberAsha100910:33 17 Jul '08  
Question.NET 3.5 only? PinmemberSIMONJONES6:32 10 Jul '08  
AnswerRe: .NET 3.5 only? Pinmemberpfemiani8:10 16 Jul '08  

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.

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