2013-04-22 35 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