0

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?

3
  • 1
    Try HttpContext.Current.Session["CurrentUser"] = value; Commented Feb 10, 2017 at 17:43
  • 1
    This is a very bad idea, though, at least for the data you're storing. Things like whether or not the user is authenticated shouldn't be stored in the session. That can be retrieved at any time via User.Identity.IsAuthenticated, anyways, so there's really no reason to. Like info like the user's email address should come from the database always. There's very little cost in retrieving the user record, especially since Entity Framework employs its own query cache, and then you're not responsible for remember to always update stuff in the session. Commented Feb 10, 2017 at 18:07
  • I totally agree to whatever you said there.But this doesnt deal with a lot of data and is merely redirecting users to different parts of the website once logged in.I am not using the user data that much here.This app is too simple to use Identity.but thanks anyways.@ChrisPratt Commented Feb 11, 2017 at 8:00

1 Answer 1

1

I think the problem is obvious. Just simple change this

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

into this

HttpContext.Current.Session["CurrentUser"] = value;
Sign up to request clarification or add additional context in comments.

2 Comments

what was I even thinking..sheesh.Thank you
@Mash, You're welcome, don't forget to mark this as answer if does solve you problem. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.