C# 在C中的HttpContext.Current.session中设置并获取会话值#

C# 在C中的HttpContext.Current.session中设置并获取会话值#,c#,session,C#,Session,我有一个名为CommonHelper的静态类 public static class CommonHelper { public static SessionObjects sessionObjects { get { if ((HttpContext.Current.Session["sessionObjects"] == null))

我有一个名为CommonHelper的静态类

 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";
当我尝试分配一个如下所示的值时

 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.

如何修复此问题?

当当前实例的
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; }
        }
    }

我不理解您的第一个
if()
检查,if
HttpContext.Current.Session[“sessionObjects”]==null
那么您将返回使用
as
运算符铸造的相同对象,但由于左侧为null,您仍然返回
null
。您需要在那里创建该对象的新实例。我使用的是静态类,那么为什么需要新实例呢?但是属性
CommonHelper。在上述情况下,SessionObject
将返回
null
。使用
var sess=CommonHelper.sessionObjects检查是否正确;if(sess==null)Console.WriteLine(“null引用”);else Console.WriteLine(“获得非空值”)。是的,你是对的,它是空的。我如何在这里创建实例并使用实例。@MaximilianGerhardt