为什么HttpContext更好地直接访问Session变量而不是Session

时间:2013-04-22 18:32:17

标签: c# asp.net .net

您可以看到此代码

[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();

2 个答案:

答案 0 :(得分:5)

没有实质性的区别。 Session上的Controller属性实现为:

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

这是一个方便的属性,所以你使用哪一个并不重要。

答案 1 :(得分:-2)

使用上下文可确保您正在访问正确的会话。在使用Session之前,应始终检查Session是否为null。这只是很好的编码实践。捷径是懒惰的,导致错误,并且是不好的做法。