Reputation: 37633
I have got some class
public static class SessionManager
{
public static UserSession UserSession
{
set
{
HttpContext.Current.Session["USER_SESSION"] = value;
}
get
{
UserSession userSession = new UserSession();
try
{
userSession = (UserSession)HttpContext.Current.Session["USER_SESSION"];
}
catch (Exception)
{
}
return userSession;
}
}
}
And I am trying to use it
var userSession = SessionManager.UserSession;
And the userSesssion
is always null
.
Any clue how it can be fixed?
Upvotes: 0
Views: 132
Reputation: 3952
I think the pattern you're actually looking for in your property looks more like this:
public static class SessionManager
{
public static UserSession UserSession
{
set
{
HttpContext.Current.Session["USER_SESSION"] = value;
}
get
{
var session = HttpContext.Current.Session;
var userSession = session["USER_SESSION"] as UserSession;
if (userSession == null)
{
userSession = new UserSession ();
session["USER_SESSION"] = userSession;
}
return userSession;
}
}
}
(I only broke out var session = HttpContext.Current.Session;
so it would all fit nicely in StackOverflow.)
Upvotes: 1
Reputation: 37633
I found solution...
I just forgot to insert under Global.asax.cs
void Session_Start(object sender, EventArgs e)
{
var userSession = new UserSession();
SessionManager.UserSession = userSession;
}
Upvotes: 0
Reputation: 31
Try this:
userSession = (UserSession)(HttpContext.Current.Session["USER_SESSION"]);
-or-
userSession = HttpContext.Current.Session["USER_SESSION"] as UserSession;
Upvotes: 1