【问题标题】:MVC 5 session after authentication身份验证后的 MVC 5 会话
【发布时间】:2016-03-05 21:02:22
【问题描述】:

我无法确定登录应用程序后会话何时首次可用以及用户身份验证。 我的目标是在用户登录到应用程序后将有关用户的一些数据保存到会话中(登录后立即,在其他任何事情发生之前),以便我以后可以使用它。 我在 VS2015 中使用默认的 MVC 5 模板。 我的登录看起来像

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl); //I jump here
            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);
        }

private ActionResult RedirectToLocal(string returnUrl)
    {
        //here I would like to save some stuff into the session, the session is available here but the user is not authenticated yet

        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Course");
    }

好的,接下来我试试 global.asax:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        //and of course here I have authenticated user but the session is null
    }

你能帮帮我吗?

【问题讨论】:

  • 为什么需要在会话中保存值?
  • 好吧,我想保存一些用户特定的数据,以便在应用程序中进一步使用。会话看起来像是保存它的好地方:-)

标签: asp.net-mvc session login asp.net-mvc-5


【解决方案1】:

ASP 将比以前更加无状态,这意味着最好不要使用会话等基于状态的对象。如果您使用 MVC5,则使用身份 2。这意味着您的身份上下文中有 ApplicationUser .因此,使用ApplicationUser,您几乎拥有所需的一切。如果您需要更多ApplicationUser,最好的方法是扩展ApplicationUser。在这种情况下,您根本不需要任何会话变量。以here为例。

【讨论】:

  • 太好了,谢谢,你是对的。我扩展了用户并且它有效!
猜你喜欢
  • 2015-07-02
  • 2015-03-25
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多