今天仔細(xì)了看了它的流程和頁面的一些邏輯? 發(fā)現(xiàn)一個(gè)以前不是常用的東西。求大俠解釋下謝謝。
圖片:
?
代碼:
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");
}
這一個(gè)ShoppingCart.GetCart(this.HttpContext);
的上下文對象,對應(yīng)的方法。
?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();
}
之后呈現(xiàn)的頁面
不明白他的業(yè)務(wù)邏輯 就是他這樣做的目的 主要是這個(gè)上下文對象? 。
2 回答

largeQ
TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
從 樓主 貼的代碼看,不傳遞 this.HttpContext ,直接在 ShoppingCart 使用這個(gè)HttpContext也是可以的。
可能是 這個(gè) ShoppingCart 購物車 畢竟是一個(gè)對象,為了到達(dá)和HttpContext 解耦,而用HttpContextBase,這樣的話,可以很好的進(jìn)行單元測試。
- 2 回答
- 0 關(guān)注
- 404 瀏覽
添加回答
舉報(bào)
0/150
提交
取消