plantpowerjames
plantpowerjames

Reputation: 385

HttpSessionStateBase vs HttpContext.Current.Session

I have a controller which sets a Session variable as below

    Session["CurrentUser"] = user;

    using (DatabaseEntities db = new DatabaseEntities())
    {
            Helpers.LoadSessionData(user, user.Tenancy.BusinessUnits.FirstOrDefault(), db);
    }

where user is an object that has been set from a database. A method is then called to load various other bits of data to the Session passing in the same user object. The opening few lines of the LoadSessionData method are as below

    currentUser = db.Users.Include(u => u.BusinessMemberships)
                             .Include(u => u.BusinessMemberships.Select(bm => bm.DivisionMemberships))
                             //.Include(u => u.Tenancy)
                             //.Include(u => u.Tenancy.BusinessUnits)
                             //.Include(u => u.Tenancy.BusinessUnits.Select(bu => bu.Settings))
                             //.Include(u => u.Tenancy.BusinessUnits.Select(bu => bu.Addresses))
                             .FirstOrDefault(u => u.UserId == currentUser.UserId && u.Void == false);

        HttpContext.Current.Session[Zahara.Web.Resources.DataKeys.SessionCurrentUser] = currentUser;

HttpContext.Current.Session is NULL when running this method and I can't for the life of me work out why???

Thanks, James

Upvotes: 0

Views: 1465

Answers (1)

Martin Fletcher
Martin Fletcher

Reputation: 168

A better solution would be to pass in the session object to the helper method as an argument.

Static 'sky hooks' are generally bad practice, and make your code harder to test.

Alternately, you could create an extension method for HttpSessionStateBase 'LoadCustomerSessionData(user, businessUnit, db)' which would be a more fluent approach.

Upvotes: 1

Related Questions