Robert-Jan
Robert-Jan

Reputation: 196

Static asp.net session for all users

I developing a ASP.net 4.0 application, with a shoppingcart. The problem is that user 1 places something, and user 2 gets it also. How can it been session sharing...

// Readonly properties can only be set in initialization or in a constructor
public static readonly ShoppingCart Instance;

// The static constructor is called as soon as the class is loaded into memory

static ShoppingCart() {
    // If the cart is not in the session, create one and put it there
    // Otherwise, get it from the session
    if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
        Instance = new ShoppingCart();
        Instance.Items = new List<CartItem>();
        HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
    } else {
        Instance = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
    }
}

Please help, i can't find a solution....

Upvotes: 0

Views: 1466

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

No, don't use this static variable:

public static readonly ShoppingCart Instance;

Replace it like this:

public static ShoppingCart Instance
{
    get
    {
        if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
            // we are creating a local variable and thus
            // not interfering with other users sessions
            ShoppingCart instance = new ShoppingCart();
            instance.Items = new List<CartItem>();
            HttpContext.Current.Session["ASPNETShoppingCart"] = instance;
            return instance;
        } else {
            // we are returning the shopping cart for the given user
            return (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];
        }
    }
}

Upvotes: 3

Related Questions