我已经使用会话创建了一个购物车,用于存储要添加到购物车中的商品。在部署后,我发现该购物车并不是该用户唯一的,其他用户正在获取其他用户添加到购物车中的商品。
我试图在会话名称中使用登录用户名,以使该会话对该用户唯一,但是它不起作用。
public class ListOfDataset
{
static ListOfDataset()
{
string username = ClaimsPrincipal.Current.Identity.Name;
// If the cart is not in the session, create one and put it there
// Otherwise, get it from the session
if (HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)] == null)
{
Instance = new ListOfDataset();
Instance.Items = new List<DataSet>();
HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)] = Instance;
}
else
{
Instance = (ListOfDataset)HttpContext.Current.Session[string.Format("ASPNETShoppingCart-{0}", username)];
}
}
}
更新后的代码,未设置else语句-对象引用中的错误,并且函数ChekIfdatasetexist始终返回false:
public class ListOfDataset
{
public static ListOfDataset Instance
{
get
{
ListOfDataset cart = null;
if (HttpContext.Current.Session["ASPNETShoppingCart"] == null)
{
cart = new ListOfDataset();
cart.Items = new List<DataSet>();
HttpContext.Current.Session["ASPNETShoppingCart"] = cart.Items;
}
else
{
cart.Items =(List<DataSet> )HttpContext.Current.Session["ASPNETShoppingCart"];
}
return cart;
}
}
public List<DataSet> Items { get; private set; }
public void AddItem(DataSet itemdataset)
{
Items.Add(itemdataset);
HttpContext.Current.Session["ASPNETShoppingCart"] = Items;
}
public bool CheckIfDataSetExist(string servicename)
{
DataSet DataSetexist = null;
if (Items != null)
{
DataSetexist = Items.Where(i => i.DataSetName == servicename).FirstOrDefault();
}
if (DataSetexist != null) return true;
return false;
}
}
答案 0 :(得分:0)
这里有两个问题。