Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# asp.net应用程序状态下的泛型集合_C#_Asp.net_Webforms_State - Fatal编程技术网

C# asp.net应用程序状态下的泛型集合

C# asp.net应用程序状态下的泛型集合,c#,asp.net,webforms,state,C#,Asp.net,Webforms,State,我想将asp.net应用程序中登录的用户存储到集合中,并将此集合存储在应用程序状态。我有一个登录页面,在Default.aspx页面加载事件中,我有以下代码:- protected void Page_Load(object sender, EventArgs e) { users = (List<Users>)HttpContext.Current.Application["loggedUsers"]; if (User.Ident

我想将asp.net应用程序中登录的用户存储到集合中,并将此集合存储在应用程序状态。我有一个登录页面,在Default.aspx页面加载事件中,我有以下代码:-

    protected void Page_Load(object sender, EventArgs e)
    {
        users = (List<Users>)HttpContext.Current.Application["loggedUsers"];

        if (User.Identity.IsAuthenticated == false)
        {
            Server.Transfer("Login.aspx");
        }

        if (User.Identity.Name != "")
        {
            users.Add(new Users { userName = User.Identity.Name.ToString() });

            HttpContext.Current.Application["loggedUsers"] = users;
        }
    }
受保护的无效页面加载(对象发送方,事件参数e)
{
users=(List)HttpContext.Current.Application[“loggedUsers”];
if(User.Identity.IsAuthenticated==false)
{
Server.Transfer(“Login.aspx”);
}
如果(User.Identity.Name!=“”)
{
添加(新用户{userName=User.Identity.Name.ToString()});
HttpContext.Current.Application[“loggedUsers”]=用户;
}
}
但是,在运行应用程序时,在登录后,将在代码中抛出一个未设置为对象实例的对象引用异常,我正在将新对象添加到列表中。如果我评论下一行:

users = (List<Users>)HttpContext.Current.Application["loggedUsers"];
users=(List)HttpContext.Current.Application[“loggedUsers”];
应用程序将相应地运行,但是,如果我们有两个用户,用户A和用户B,并且用户A登录,他将被添加到列表中,但是一旦用户B登录,它将覆盖用户A

在我的Web服务中,我有以下方法,它将返回当前登录的用户列表,这些用户工作正常

    [WebMethod(EnableSession = true)]
    public List<Users> getLoggedInUsername()
    {
        return (List<Users>)Application["loggedUsers"];
    }
[WebMethod(EnableSession=true)]
公共列表getLoggedInUsername()
{
返回(列表)应用程序[“loggedUsers”];
}

问题在于,当您的第一个用户输入时,您在应用程序中没有使用loggedUser键的值。通常的做法是在强制转换前检查NULL

      List<User> user = null;
      if(HttpContext.Current.Application["loggedUsers"] == null)
      {
         user = new List<User>();
      }
      else
      {
         user = (List<User>)HttpContext.Current.Application["loggedUsers"]; 
      }
列表用户=null;
if(HttpContext.Current.Application[“loggedUsers”]==null)
{
用户=新列表();
}
其他的
{
user=(List)HttpContext.Current.Application[“loggedUsers”];
}

铸造钥匙之前,请检查钥匙是否可用。HttpContext.Current.Application[“loggedUsers”]!=无效的如果为空,则创建新列表,否则强制转换并使用它