你可以看到這個代碼爲什麼HttpContext的是更好地訪問會話變量比直接會話
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
...
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();
}
那麼,爲什麼我們不能僅僅直接使用Session[CartSessionKey]
?
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = Session[CartSessionKey].ToString();
你剛剛知道這是如何從實驗中實現的,還是在某處記錄的? +1雖然你的主要觀點,這裏沒有真正的區別。 – jadarnel27 2013-04-22 18:50:08
ReSharper有一個集成的反編譯器,它使這種事情變得微不足道。另外,如果您在VS中包含源服務器支持,則源代碼[可從MS獲得](http://msdn.microsoft.com/zh-cn/library/cc667410.aspx)。 – 2013-04-22 18:59:13
啊,非常酷 - 我不知道。感謝您的跟蹤。 – jadarnel27 2013-04-22 19:28:59