ASP.NET MVC: Sharing a Session between controllers


Most web programming languages have some mechanism to store shared variables across pages throughout the site. This is usually called a Session and can be used to store some state in what is otherwise a stateless environment. In tradtional ASP.NET WebForms applications the session state was generally available throughout all pages in your site.

In ASP.NET MVC the session state is also available but is sandboxed (in a way) to only be available within the current controller that you're in. If you want to share that session with other controllers in your site you will need to put a middle object in place to link the information between controllers. Luckly, this can be done very easily.

In your site you'll want to declare a base controller class that will implement a session property. The next step will be having all of your controllers inherit from this class (that need to access this session).

C# BaseController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyTestApp.App_Utilities
{
    public class BaseController : Controller
    {

        /// 
        /// A session object that can/will be shared between all controllers that inherit from
        /// this base.
        /// 
        public System.Web.SessionState.HttpSessionState SharedSession
        {
            get
            {                
                return System.Web.HttpContext.Current.Session;
            }
        }

    }
}

C# Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace MyTestApp.Controllers
{
    public class DefaultController : MyTestApp.App_Utilities.BaseController
    {
        // GET: Default
        public ActionResult Index()
        {
            // This value, if accessed through SharedSession in other controllers will
            // be accessible.
            this.SharedSession["TestValue"] = "Hello World";
        }
    }
}

Important Note

The SharedSession is it's own object, it does not overlap with the Session that is provided in a controller. In short, if you put something in "this.SharedSession" you will need to access it from "this.SharedSession".

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.