2013-04-22 32 views
0

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

回答

5

没有实质性差异。该Session财产上Controller被实现为:

if (this.HttpContext != null) 
    return this.HttpContext.Session; 
else 
    return null; 

这是一个方便的特性,所以它不会不管你使用哪一个。

+0

你刚刚知道这是如何从实验中实现的,还是在某处记录的? +1虽然你的主要观点,这里没有真正的区别。 – jadarnel27 2013-04-22 18:50:08

+1

ReSharper有一个集成的反编译器,它使这种事情变得微不足道。另外,如果您在VS中包含源服务器支持,则源代码[可从MS获得](http://msdn.microsoft.com/zh-cn/library/cc667410.aspx)。 – 2013-04-22 18:59:13

+0

啊,非常酷 - 我不知道。感谢您的跟踪。 – jadarnel27 2013-04-22 19:28:59

-2

使用上下文保证您正在访问正确的会话。在使用它之前,您应该始终检查您的Session是否为空。这只是良好的编码习惯。捷径是偷懒,导致错误,是不好的做法。

+2

'Controller.Session'返回'HttpContext.Session'(带有空格检查),所以你的回答没有任何意义。 – 2013-04-22 18:36:55