asp mvc5 Identity在登录时附加cookie,并在注销时清除

时间:2019-03-21 09:44:24

标签: asp.net-mvc asp.net-identity session-cookies

我正在使用默认的Identity在ASP.net MVC5上工作
我有两个AspNetUsers的子表,分别是studentsTeachers 两者都使用foreign key user_id引用AspNetuser
登录时,我要进行2个查询,并将Student.ID和/或Teacher.ID设为Session变量。
它正在工作,但是当我关闭浏览器时,即使AspnetUser仍然登录,会话也会清除。
我认为Asp.Net默认Identity会将用户信息登录到Cookie中
寻找最佳解决方案,应该有多少Cookie寿命等等
我当前的代码是

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        } 

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
/***************************my code starts here************/
           var userID = UserManager.FindByEmail(model.Email).Id;

           Teacher teacher = db.Teachers.Where(t => t.user_id == UserID).FirstOrDefault();
           if(teacher != null)
           {
                Session["t_id"]             = teacher.id;
                Session["t_section_id"]     = teacher.section_id;                  
           }

           Student student= db.Students.Where(s => s.user_id == UserID).FirstOrDefault();
           if (student!= null) 
           {
                Session["s_id"]        = student.id;
                Session["s_class_id"]  = student.class_id; 
           }
/***************************my code ends here************/
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

并在注销时删除了这些Session变量

public ActionResult LogOff()
    {


AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

        Session.Contents.Remove("t_id");
        Session.Contents.Remove("t_section_id");
        Session.Contents.Remove("s_id");
        Session.Contents.Remove("s_class_id"); 
        return RedirectToAction("Index", "Home");
    }

0 个答案:

没有答案