简体   繁体   English

mvc C# session 多次登录后丢失

[英]Mvc C# session lost after multiple login

I'm creating a simple website for multiple users.我正在为多个用户创建一个简单的网站。 Now i'm trying to make the profile of each one so when they login they can see their data.现在我正在尝试制作每个人的个人资料,以便他们登录时可以看到他们的数据。 The problem is that once logged in with one user and i login with another one my session gets "overwritten" and the new user become the old one.问题是,一旦用一个用户登录,而我用另一个用户登录,我的 session 就会被“覆盖”,新用户就会变成旧用户。 So i think i'm messing up with the session part.所以我想我搞砸了 session 部分。

I'm telling you what i've done.我告诉你我做了什么。

  1. Inside the login controller i call a the Login function, passing username and password.在登录 controller 中,我调用登录 function,传递用户名和密码。

  2. Then i validate the user credentials to the database and if the user has been authenticated i do:然后我验证数据库的用户凭据,如果用户已经过身份验证,我会这样做:

    new_session = new UserSession();新会话 = 新用户会话();

    new_session.SessionSet(obj); new_session.SessionSet(obj);

Inside the "SessionSet" i just initialize some variables i need:在“SessionSet”中,我只是初始化了一些我需要的变量:

this.id_account          = obj.id_account;
this.id_user             = obj.id_user;
this.username            = obj.username;
  1. At this point i return the new_session to the Controller and if it is not null i just add it to the session:此时我将 new_session 返回到 Controller,如果不是 null,我只需将其添加到 session:

    Session.Add("user", new_session); Session.Add("user", new_session);

The problem now is how can i get this specific object form: views, classes and controllers?现在的问题是我怎样才能得到这个特定的 object 形式:视图、类和控制器? If i write in a view:如果我写在一个视图中:

(((UserSession)Session["user"]).username)

I get only the "user" object so when 2 users log in at the same time, the session refer always to the "user" one.我只得到“用户” object 所以当两个用户同时登录时,session 总是指“用户”之一。

I googled it but i can't find an answer that fits to my needs.我用谷歌搜索了它,但我找不到适合我需要的答案。

  1. get database UserSession data获取数据库 UserSession 数据
  2. see user with this useID Is logged in查看具有此 useID 的用户已登录
  3. if user logged in {not allaw login} else {allow login}如果用户登录 {不允许登录} 否则 {允许登录}

or write data in session with timeout或在 session 中写入数据超时

if(Session["users"] != null)
{
    List<UserSession> users = (List<UserSession>)Session["users"];
    var finduser = users.Where(a=> a.id_user == newUser.id_user).FirstOrDefault();
    if(findUser == null)
    {
        //add user into session
    }
}
else
{
    Session.Add("users",newUser);
}

and web.config file set timeout logout and session equal和 web.config 文件设置超时注销和 session 相等

<sessionState mode="InProc" timeout="20"></sessionState>
<authentication mode="Forms">
  <forms loginUrl="/Pages/Default" timeout="20" slidingExpiration="true" />
</authentication>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM