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.Ses开发者_JS百科sion["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)
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>();
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.
精彩评论