ASP.NET MVC 4会员“记住我”如何运作?

时间:2013-11-27 23:15:04

标签: asp.net-mvc-4 asp.net-membership remember-me

我正在使用ASP.NET MVC 4中的标准成员资格功能。

我有一个登录表单,当用户成功登录时,会从数据库中检索一些用户信息,并将其放入我在应用程序某些部分使用的Session变量中。

我的问题如下:

当我激活“记住我”选项时,它可以正常工作,但是永远不会加载会话变量,因为在登录验证过程中实际上正在加载该变量,现在正在跳过它。

我的问题是:有没有办法抓住“记住我”验证过程来放置我的自定义代码,它将加载我需要的会话变​​量? (或者可能在“记住我”的cookie中添加更多信息,以后可以使用?)

谢谢

1 个答案:

答案 0 :(得分:5)

在您的方案中,您可以使用 Global.asax的Session_Start 事件来填充用户的信息。

public class Global : System.Web.HttpApplication
{
    protected void Session_Start(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null &&
            HttpContext.Current.User.Identity.IsAuthenticated &&
            HttpContext.Current.Session["MyUserInfo"] == null)
        {
            // Get the user's information from database and save it to Session.
            HttpContext.Current.Session["MyUserInfo"] = "johndoe";
        }
    }
}