Asp.net-mvc – ASP.NET MVC – How to access Session data in places other than Controller and Views

asp.net-mvcsession

We can access session data in controllers and views like this:

Session["SessionKey1"]

How do you access Session values from a class other than a controller or view?

Best Answer

I'd use dependency injection and pass the instance of the HttpContext (or just the session) to the class that needs access to the Session. The other alternative is to reference HttpContext.Current, but that will make it harder to test since it's a static object.

   public ActionResult MyAction()
   {

       var foo = new Foo( this.HttpContext );
       ...
   }


   public class Foo
   {
        private HttpContextBase Context { get; set; }

        public Foo( HttpContextBase context )
        {
            this.Context = context;
        }

        public void Bar()
        {
            var value = this.Context.Session["barKey"];
            ...
        }
   }