亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

mvc音樂商店的購物的一段代碼解析 路過的大俠幫忙看看 謝謝!沒什么豆

mvc音樂商店的購物的一段代碼解析 路過的大俠幫忙看看 謝謝!沒什么豆

www說 2018-12-07 08:28:01
今天仔細了看了它的流程和頁面的一些邏輯? 發現一個以前不是常用的東西。求大俠解釋下謝謝。 圖片: ? 代碼: public ActionResult AddToCart(int id) { // Retrieve the album from the database var addedAlbum = storeDB.Albums .Single(album => album.AlbumId == id); // Add it to the shopping cart var cart = ShoppingCart.GetCart(this.HttpContext); cart.AddToCart(addedAlbum); // Go back to the main store page for more shopping return RedirectToAction("Index"); } 這一個ShoppingCart.GetCart(this.HttpContext); 的上下文對象,對應的方法。 ?public const string CartSessionKey = "CartId"; public static ShoppingCart GetCart(HttpContextBase context) { var cart = new ShoppingCart(); cart.ShoppingCartId = cart.GetCartId(context); return cart; } ? // We're using HttpContextBase to allow access to cookies. public string GetCartId(HttpContextBase context) { if (context.Session[CartSessionKey] == null) { if (!string.IsNullOrWhiteSpace(context.User.Identity.Name)) { context.Session[CartSessionKey] = context.User.Identity.Name; } else { // Generate a new random GUID using System.Guid class Guid tempCartId = Guid.NewGuid(); // Send tempCartId back to client as a cookie context.Session[CartSessionKey] = tempCartId.ToString(); } } return context.Session[CartSessionKey].ToString(); } 之后呈現的頁面 不明白他的業務邏輯 就是他這樣做的目的 主要是這個上下文對象? 。
查看完整描述

2 回答

?
largeQ

TA貢獻2039條經驗 獲得超8個贊

從 樓主 貼的代碼看,不傳遞 this.HttpContext ,直接在 ShoppingCart 使用這個HttpContext也是可以的。 可能是 這個 ShoppingCart 購物車 畢竟是一個對象,為了到達和HttpContext 解耦,而用HttpContextBase,這樣的話,可以很好的進行單元測試。
查看完整回答
反對 回復 2018-12-09
  • 2 回答
  • 0 關注
  • 399 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號