Статическая сессия asp.net для всех пользователей - PullRequest
0 голосов
/ 15 октября 2011

Я разработал приложение ASP.net 4.0 с корзиной для покупок. Проблема в том, что пользователь 1 размещает что-то, а пользователь 2 тоже это получает. Как это может быть сессия обмена ...

// 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"];
    }
}

Пожалуйста, помогите, я не могу найти решение ....

1 Ответ

2 голосов
/ 15 октября 2011

Нет, не используйте эту статическую переменную:

public static readonly ShoppingCart Instance;

Замените ее следующим образом:

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"];
        }
    }
}
...