2011-08-06 16 views
7

存在しないのですか?「セッションは、」私はセッションを使用していますが、私はラインでのエラーを持って、次のコードを、持っている現在のコンテキストで

using System; 
using System.Data; 
using System.Configuration; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 

using System.Collections.Generic; 
using System.Web.SessionState; 
/// <summary> 
/// Summary description for ShoppingCart 
/// </summary> 
public class ShoppingCart 
{ 
    List<CartItem> list; 
    public ShoppingCart() 
    { 
     if (Session["ShoppingCart"] == null) 
      list = new List<CartItem>(); 
     else 
      list = (List<CartItem>)Session["ShoppingCart"]; 
    } 
} 
+0

を働いていましたか?あなたはコンストラクタを意味しますか?その他のクラス – Adham

+1

非セッションページまたはスレッドから呼び出します。 – Aristos

答えて

15

問題は、クラスがページから継承しないことです。
変更 パブリッククラスShoppingCartの

パブリッククラスのShoppingCartへ:ページ

、それは

if (Session["ShoppingCart"] == null) 
+4

ページが適切な解決策のように見えないときに継承するページ... – Peter

34

使用を仕事のどちらかにする必要がありますPageを継承してクラスをPageに変換するか、またはSessionを渡すか、HttpContext.Current.Sessionを使用してください。

+2

しかし、私はこの例外System.NullReferenceException ..を得る! – Adham

+0

セッションや何かを放棄しましたか?私の推測は、HttpContext.CurrentがnullかHttpContext.Current.Sessionがnullであるということです。しかし、私は理由が分かりません。理由は少ししかありません。 – Peter

+0

このHttpContext.Current.Session ["ShoppingCart"]は素晴らしかったです。ありがとう:) – Umitk

7

if (HttpContext.Current == null || 
    HttpContext.Current.Session == null || 
    HttpContext.Current.Session["ShoppingCart"] == null) 

代わりにあなたを

+2

しかし、私はこの例外System.NullReferenceException ..を得る! – Adham

+0

ページが適切な解決策のように見えないときに継承するページ... – Peter

0

サラム。このような私の場合のみのtry-catchブロックの修正問題で

、:

protected void Application_AcquireRequestState(object sender, EventArgs e) 
    { 
     /// Using from Try-Catch to handle "Session state is not available in this context." error. 
     try 
     { 
      //must incorporate error handling because this applies to a much wider range of pages 
      //let the system do the fallback to invariant 
      if (Session["_culture"] != null) 
      { 
       System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Session["_culture"].ToString()); 
       //it's safer to make sure you are feeding it a specific culture and avoid exceptions 
       System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Session["_culture"].ToString()); 
      } 
     } 
     catch (Exception ex) 
     {} 
    } 
0

新しいページを作成し、壊れたページから、その上のすべてを貼り付け、動作しませんでした。何がVisual Studioを閉じて再オープンしたのですか?壊れたページが

0

その後、どの方法あなたが直接セッションを使用したい場合は、単に次の名前空間を追加

using system.web.mvc

関連する問題