你可以看到这个代码为什么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