RobHurd
RobHurd

Reputation: 2061

How to persist logged in user data for entire session?

I'm creating a practice admin application using MVC4, but I'm not sure the best method to persist the logged in user data for the entire lifetime of the session so that it will be accessible to all views & controllers.

For example, I desire a user to log in, then download the user data from the database, and for the entire session I want to maintain the User model (Name, Database ID etc) so that it's accessible throughout the entire web application until the user is logged out.

Is the best approach to store this data in an encrypted cookie? Or is there a way of using a Static Class?

Currently I've read about using ViewModel Base class like so:

    public abstract class ViewModelBase
    {
        public UserModel User { get; set; }
    }

Then all of my ViewModels can inherit the base class, thus providing access to the user data model:

public class AllEmployeesViewModel : ViewModelBase
{
    public List<EmployeeModel> Employees { get; set; } 
}

However, if in one Controller action I set the user data, it will only be lost when loading another Controller Action.

To me it seems a waste of resources & will increase load times to have to keep downloading the user data from the database in every action.

All advice is much welcome for this new web programmer. If I've missed any important details, please do request it and I will try my best to answer.

Upvotes: 0

Views: 1210

Answers (2)

Ross Bush
Ross Bush

Reputation: 15185

I would abstract the Session for you application in a class in a way it is accessible to your controllers. Maybe an web application core class.

namespace MyApplication.Core
{
    public class MySession
    {
        private const string _SessionName = "__MY_SESSION__";

        private MySession() { }

        public static MySession Current
        {
            get
            {
                MySession session =
                  (MySession)HttpContext.Current.Session[_SessionName];
                if (session == null)
                {
                    session = new MySession();                
                    HttpContext.Current.Session[_SessionName] = session;
                }
                return session;
            }
        }        
        public UserModel CurrentUser { get; set; }

    }
}

Somewhere in your login controller logic path

public void SomeLoginFunction(string userName,string password)
{
    //DO AUTHENTICATION STUFF
    MySession.Current.CurrentUser=aCurrentUserFromDB;
}

In your base class

public class ViewModelBase
{
     public UserModel User { get{return {MySession.Current.CurrentUser;}  }
}

Upvotes: 0

TGH
TGH

Reputation: 39278

You should look into SessionState to store data for the duration of the user's browser session.

http://msdn.microsoft.com/en-us/library/vstudio/ms178581(v=vs.100).aspx

Upvotes: 4

Related Questions