Mash
Mash

Reputation: 159

Assign Session value using properties in mvc

So, here is the idea.I have a SessionCache class which is to get and set session variables which is simple user info.So I want to set values to session once user is successfully logged in and use this class to get session values throughout the application.But somehow I am not able to set the values to session variable in the SessionCache class.

public class SessionCache
{
    public static string SessionID
    {
        get
        {
            return HttpContext.Current.Session.SessionID;
        }
    }
    public static CurrentUserVM CurrentUser
    {
        get
        {
            return (CurrentUserVM)HttpContext.Current.Session["CurrentUser"];
        }
        set
        {
            HttpContext.Current.Session["CurrentUser"] = CurrentUser;
        }
    }
}

So, Im trying to set values using the above class in login action as below:

CurrentUserVM currentUser = new CurrentUserVM();
currentUser.User = db.userClass.FirstOrDefault(m => m.EmailID.Equals(objLogin.EmailID));
currentUser.isAuthenticated = true;
SessionCache.CurrentUser = currentUser;
SessionCache.CurrentUser.isAuthenticated = currentUser.isAuthenticated;

but still the SessionCache.CurrentUser remains null.Is there something wrong with my code?

Upvotes: 0

Views: 763

Answers (1)

jtabuloc
jtabuloc

Reputation: 2535

I think the problem is obvious. Just simple change this

HttpContext.Current.Session["CurrentUser"] = CurrentUser;

into this

HttpContext.Current.Session["CurrentUser"] = value;

Upvotes: 1

Related Questions