Adding Item to Generic List in Session

时间:2015-09-14 15:03:09

标签: c# session

I have a session helper so that my session vars are strongly typed:

public sealed class SessionHelper
{
    private static HttpSessionState Session
    {
        get
        {
            return HttpContext.Current.Session;
        }
    }

    public static List<TestObject> Tests
    {
        get
        {
            List<TestObject> objects = new List<TestObject>();
            if (Session["Tests"] != null)
            {
                objects = (List<TestObject>)Session["Tests"];
            }

            return objects;
        }

        set
        {
            Session["Tests"] = value;
        }
    }
}

Now I am trying to add an item to theTestObjects List so I thought I could just do:

SessionHelper.Tests.Add(new TestObject("Test name", 1));

But when I step through the code and look at the SessionHelper.Tests after the above line is run, the list count remains at 0.

If I do:

List<TestObject> tests = SessionHelper.Tests;
tests.Add(new TestObject(testName, version));
SessionHelper.Tests = tests;

Then it works properly.

Why can't I add the test object directly to the SessionHelper?

1 个答案:

答案 0 :(得分:4)

Session["Tests"] is null when you start. Therefore SessionHelper.Tests returns a new, empty list; however, this new list is not in the session object yet. Therefore SessionHelper.Tests will return a new, empty list every time. Store the new list in the session object after creating it.

public static List<TestObject> Tests
{
    get
    {
        List<TestObject> objects = (List<TestObject>)Session["Tests"];
        if (objects == null)
        {
            objects = new List<TestObject>();
            Session["Tests"] = objects; // Store the new list in the session object!
        }
        return objects;
    }

    set // Do you still need this setter?
    {
        Session["Tests"] = value;
    }
}