Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 341
xraminx Avatar asked Apr 09 '09 17:04

xraminx


3 Answers

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"];             ...         }    } 
like image 79
tvanfosson Avatar answered Sep 28 '22 05:09

tvanfosson


You just need to call it through the HttpContext like so:

HttpContext.Current.Session["MyValue"] = "Something"; 
like image 21
Nick Berardi Avatar answered Sep 28 '22 04:09

Nick Berardi


Here is my version of a solution for this problem. Notice that I also use a dependency injection as well, the only major difference is that the "session" object is accessed through a Singleton

private iSession _Session;

private iSession InternalSession
{
    get
    {

        if (_Session == null)
        {                
           _Session = new SessionDecorator(this.Session);
        }
        return _Session;
    }
}

Here is the SessionDecorator class, which uses a Decorator pattern to wrap the session around an interface :

public class SessionDecorator : iSession
{
    private HttpSessionStateBase _Session;
    private const string SESSIONKEY1= "SESSIONKEY1";
    private const string SESSIONKEY2= "SESSIONKEY2";

    public SessionDecorator(HttpSessionStateBase session)
    {
        _Session = session;
    }

    int iSession.AValue
    {
           get
        {
            return _Session[SESSIONKEY1] == null ? 1 : Convert.ToInt32(_Session[SESSIONKEY1]);
        }
        set
        {
            _Session[SESSIONKEY1] = value;
        }
    }

    int iSession.AnotherValue
    {
        get
        {
            return _Session[SESSIONKEY2] == null ? 0 : Convert.ToInt32(_Session[SESSIONKEY2]);
        }
        set
        {
            _Session[SESSIONKEY2] = value;
        }
    }
}`

Hope this helps :)

like image 38
Smoothcity Avatar answered Sep 28 '22 04:09

Smoothcity