.Net Shopping Cart Session accessible across different browsers by different users?

884 Views Asked by At

Using following method to create Shopping Cart Session http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/

Now running locally on my machine where sessionstate mode is inProc by default, all seems to perform fine.

I'm writing an application which I've just placed up on hosting provider (shared hosting environment etc). Their default sessionstate is stateserver so I had to serialise the classes to fit in with this. It's using cookies.

The basket (adding,removing etc) works fine but I'm seeing some odd things happen regarding the persistency of the session.

On my local machine, if I access the site in 2 separate browsers, if I add items in IE, I can see them in Firefox when I refresh. This doesn't make any sense to me since cookies are per browser.

Plus I thought that when a session was generated, its id would be unique so there is no way that one user should be able to see anothers session data (unless tabbed in same browser perhaps)

Even worse, if I start adding/removing items in IE and doing likewise in Firefox, both of them show very random cart results every time you refresh the browser.

Any ideas? I'm stumped! The code for generating the class and session is pretty much what its the link above.

1

There are 1 best solutions below

2
On BEST ANSWER

I didn't go through the sample in great detail, but I would be quite concerned about the singleton implementation:

public static readonly ShoppingCart Instance;

Since this is an ASP.Net web application, you are going to have a one shopping cart for every single user that connects to the website as opposed to one instance for each user session. This is obviously not a good design.

In fact, there is at least one user in the comments section that asked: "Please tell me how to create new cart rather than using same cart for all the users."

I think that you would be better off with something along these lines:

Change:

public static readonly ShoppingCart Instance;  

to:

// Method to retrieve the current user's shopping cart, stored in their session
public static ShoppingCart Instance() {

    ShoppingCart value;

    // 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) {  
        value = new ShoppingCart();  
        value.Items = new List<CartItem>();  
        HttpContext.Current.Session["ASPNETShoppingCart"] = value;  
    } else {  
        value = (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"];  
    }  
    return value;
}  

Then remove the static constructor altogether.

The only change that you will have to make in the rest of your code is ShoppingCart.Instance. becomes ShoppingCart.Instance().