将匿名用户转换为注册用户处理

在Global.asax全局变量中对匿名用户有进行了处理,我当初也在想,这个匿名用户买了东西,要下单的时候需要登录,登录后它买的东东怎么转换给登录的用户呢?

下面先来看下这段处理代码吧:

 1 //将匿名用户转换为注册用户处理
2 void Profile_MigrateAnonymous(Object sender, ProfileMigrateEventArgs e) {
3 ProfileCommon anonProfile = Profile.GetProfile(e.AnonymousID);//获取匿名用户的Profile对象
4
5 // Merge anonymous shopping cart items to the authenticated shopping cart items
6 foreach (CartItemInfo cartItem in anonProfile.ShoppingCart.CartItems)
7 Profile.ShoppingCart.Add(cartItem);
8
9 // Merge anonymous wishlist items to the authenticated wishlist items
10 foreach (CartItemInfo cartItem in anonProfile.WishList.CartItems)
11 Profile.WishList.Add(cartItem);
12
13 // Clean up anonymous profile
14 //删除匿名用户信息
15 ProfileManager.DeleteProfile(e.AnonymousID);
16 AnonymousIdentificationModule.ClearAnonymousIdentifier();//删除匿名用户标识
17
18 // Save profile
19 Profile.Save();
20 }

这里用到了ProfileCommon这个类,上节我已经对其做了解释,当ASP.NET运行时,他会先创建这个类,它是继承ProfileBase这个基类的。

代码3是用了多态的机制来实例化的。

那么代码行6的anonProfile.ShoppingCart.CartItems这个CartItems应该装载了些什么呢。先不看代码,我猜是要记录匿名用户所购买的Items及相应的Quatitys

和Total。那么是不是这样呢?来看看BLL.Cart这个类吧:

private Dictionary<string, CartItemInfo> cartItems =new Dictionary<string, CartItemInfo>();

BLL.Cart定义了一个私有的字段Dictionary,它是一个泛型集合,跟IList一样是泛型的。从上面的定义我们可以看出Dictionary<TKey,TValue>,的键值Tkey是string类型的itemId,而Tvalue是CartItemInfo类型的CartItemInfo。这样来存储购物车 的信息很方便。

上面的代码应该还好理解吧,之前不理解行6行7,是因为我对Profile还了解不够吧。现在是这样理解的:我们先用已经生产的ProfileCommon这个对象记录匿名用户购买的东东(是CartItemInfo类型的),然后再用Profile吧它转换为注册用户的,这里是Profile可以记录随时记录心注册的用户吧。

 

然后呢,上面那段代码不是用到了Cart中的Add(CartItemInfo x)函数吗?那么现在就我们来看看这段函数代码是怎么记录我们的购物车信息吧(我做了详细注释了):

publicvoid Add(CartItemInfo item) {
CartItemInfo cartItem;
if (!cartItems.TryGetValue(item.ItemId, out cartItem))//参数一item.ItemId是键值,
//如果Dictionary包含键值返回true,cartItem应该是返回的值,这里的话应该是ItemId,
//但我不明白cartItem怎么匹配ItemId?否则false。
//这个问题我可能已经明白了,因为如果键值已经存在了,我们就输出了cartItem类型,
//这个应该相当于引用类型,我们再后面的数量添加自然也会添加到字典中了
cartItems.Add(item.ItemId, item);//如果字典中不包含ItemId,将item.ItemId和item添加到词典中
else
cartItem.Quantity
+= item.Quantity;//如果ItemId在字典中可以找到,就更新ItemId对应的宠物数量,//
//但是为什么购物车包含那么都属性,而这里只添加了他的数量呢?
//经过思考,我现在也可能明白为什么只添加数量了,因为你键值既然存在了,
//那么你就有相应的宠物的信息啦,那么你需要知道的是数量有没有变量罢了
}

我觉得这个购物车是BLL中最有想法的一部分了。

 

7-19-2011补

那么Profile的匿名用户到底是怎么转换为注册用户的呢?这个转换机制有点复杂,我们的匿名用户是存在于浏览器的Cookie中的,且有一个Profile与其相对应,但这个Profile不写入数据库的,应该只用来做判断的。当你登录后,就会又生成一个Profile了,这个时候要做用户的转换了,就要用到Global.asax这个文件了。那么就是触发这个Profile_MigrateAnonymous事件了,那么这个事件到底是属于哪个类的呢?答案是:ProfileModule类。这些Profile**类与Membership类到底有什么联系呢?不然他们登录的时候就会找到ProfileModule这个类来触发这个事件?待续。

 

 

 

 

 

 

 

 

 

 

posted @ 2011-07-15 12:23  小霖2012  阅读(434)  评论(0编辑  收藏  举报