2016-09-07 7 views
0

私はCommoonHelperという静的クラスを持っています。C#のHttpContext.Current.Sessionでセッション値を設定して取得する

public static class CommonHelper 
    { 

     public static SessionObjects sessionObjects 
     { 
      get 
      { 

       if ((HttpContext.Current.Session["sessionObjects"] == null)) 
       { 

        return null; 
       } 
       else 
       { 
        return HttpContext.Current.Session["sessionObjects"] as SessionObjects; 
       } 
      } 
      set { 
       HttpContext.Current.Session["sessionObjects"] = value; 
      } 
     } 

    } 

SessionObjectsクラスでは、以下のようにget/setのプロパティを定義しました。

public class SessionObjects 
    { 
     public int UserId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string UserName { get; set; } 
     public string DisplayName 
     { 
      get 
      { 
       return FirstName + "" + LastName; 
      } 
     } 
    } 

次のような値を割り当てようとします。

CommonHelper.sessionObjects.LastName = "test"; 

以下の例外を投げます。

System.NullReferenceException: Object reference not set to an instance of an object. 

どうすればこの問題を解決できますか?

+0

私は理解していない、あなたの()は 'チェックすると最初の'、 '場合HttpContext.Current.Session [「sessionObjectsは」] == null'なのでその後、あなたは' as'演算子とキャストが同じオブジェクトを返します。しかし、左側がnullなので、あなたはまだ 'null'を返します。そこにそのオブジェクトの新しいインスタンスを作成する必要があります。 –

+0

静的クラスを使用していますが、新しいインスタンスが必要なのはなぜですか? –

+0

しかし、上記の場合、 'CommonHelper.sessionObjects'プロパティは' null'を返します。 'var sess = CommonHelper.sessionObjects;でチェックしてください。 if(sess == null)Console.WriteLine( "null参照。");それ以外の場合はConsole.WriteLine( "nullではありません。"); ' –

答えて

3

現在のインスタンスのSessionObjectsオブジェクトがnullの場合、SessionObjectsクラスの新しいインスタンスを作成してみてください。

public static class CommonHelper 
    {  
     public static SessionObjects sessionObjects 
     { 
      get 
      { 
       if ((HttpContext.Current.Session["sessionObjects"] == null)) 
        HttpContext.Current.Session.Add("sessionObjects", new SessionObjects()); 
       return HttpContext.Current.Session["sessionObjects"] as SessionObjects; 
      } 
      set { HttpContext.Current.Session["sessionObjects"] = value; } 
     } 
    } 
+0

ありがとう –

関連する問題