今天仔細了看了它的流程和頁面的一些邏輯? 發現一個以前不是常用的東西。求大俠解釋下謝謝。
圖片:
?
代碼:
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,這樣的話,可以很好的進行單元測試。
- 2 回答
- 0 關注
- 399 瀏覽
添加回答
舉報
0/150
提交
取消