BrunoLM
BrunoLM

Reputation: 100312

How to access the same session from different places?

I have a View which is using

Session["Something"] = 1;

And I have a class inside a class library project that tries to get this value from the session using

HttpContext.Current.Session["Something"]

But it retuns null.

public ActionResult Index()
{
    Session["Something"] = 1;
    var fromLib = (new MyLibClass()).GetSession("Something"); // null
    var fromHere = Session["Something"]; // 1
}

// Class library project
public object GetSession(string key)
{
    return HttpContext.Current.Session[key];
}

How can I get the value from the session? Or is there a way to save a value and retrieve in another place (without database or system files)

Upvotes: 0

Views: 3749

Answers (2)

BrunoLM
BrunoLM

Reputation: 100312

There are two sessions

Session (refers to the view session)
HttpContext.Current.Session (refers to context session)

Using HttpContext.Current.Session everywhere works as they are the same. I made a class to help me access the session values the way I want, so I can just call it without worrying about the correct session.

Upvotes: 1

Xaqron
Xaqron

Reputation: 30837

You don't need Session object.

Although Session is good for holding variables inside an asp.net application you can implement your own session object for using inside your class libraries which is light and fast and internal to your code:

Dictionary<string, object> MySession = new Dictionary<string, object>();
MySession.Add("VariableName", myObject);
MyLib.Pass(MySession);

Try to keep it more specific if possible i.e. if you just pass MyClass to your library then:

Dictionary<string, MyClass> MySession = new Dictionary<string, MyClass>();

Upvotes: 1

Related Questions