Asp.net mvc 3 如何在整个asp.net mvc(razor 3)应用程序中存储值?

Asp.net mvc 3 如何在整个asp.net mvc(razor 3)应用程序中存储值?,asp.net-mvc-3,session-state,Asp.net Mvc 3,Session State,例如,如果用户登录,存储用户ID和/或他/她的角色/组的最佳方法是什么?最明显的方法是cookies和session?还有什么其他选项?如果要存储每个用户的值,I会话是最佳选项。会话是基于每个用户/浏览器创建的。每个用户都有他/她自己的会话对象,因此通过这种方式,您可以在应用程序中保留用户角色信息,直到会话结束 我绝对不建议将用户安全信息存储在cookie中,因为这将在应用程序中造成一个很大的安全漏洞。至少,使用表单身份验证,您可以将用户id和角色放入Formst身份验证票证中 下面是我如何做到

例如,如果用户登录,存储用户ID和/或他/她的角色/组的最佳方法是什么?最明显的方法是cookies和session?还有什么其他选项?

如果要存储每个用户的值,I会话是最佳选项。会话是基于每个用户/浏览器创建的。每个用户都有他/她自己的会话对象,因此通过这种方式,您可以在应用程序中保留用户角色信息,直到会话结束


我绝对不建议将用户安全信息存储在cookie中,因为这将在应用程序中造成一个很大的安全漏洞。

至少,使用表单身份验证,您可以将用户id和角色放入Formst身份验证票证中

下面是我如何做到这一点的一个例子:

    public static HttpCookie CreateCookie(IUserIdValue userId, string name, IEnumerable<int> group, bool isPersistent = false)
    {
        var user = new AuthenticationTicketData() { Groups = @group, UserId = userId };
        var ft = new FormsAuthenticationTicket(2, name, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout),
                                               isPersistent, user.Pack());
        var ck = new HttpCookie(FormsAuthentication.FormsCookieName)
                     {
                         Value = FormsAuthentication.Encrypt(ft),
                         Path = FormsAuthentication.FormsCookiePath,
                         Domain = FormsAuthentication.CookieDomain
                     };
        if (isPersistent)
        {
            ck.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
        }
        return ck;
    }


 public static string Pack(this AuthenticationTicketData data)
    {
        if (data == null) throw new ArgumentNullException("data");
        return String.Format("{0};{1}",PackUserId(data.UserId),string.Join(",",data.Groups));
    }

    static string PackUserId(IUserIdValue uid)
    {
        if (uid == null) throw new ArgumentNullException("uid");
        var tpn = uid.GetType().GetFullTypeName();
        return String.Format("{0}|{1}",tpn,uid.ToString());
    }

 public static HttpCookie SetAuthCookie(this HttpResponse response,IUserIdValue userId, string name, IEnumerable<int> group, bool isPersistent = false)
    {
        var ck = CreateCookie(userId, name, group, isPersistent);
        response.AppendCookie(ck);
        return ck;
    }

另一种方法是保持用户会话与数据库中的会话无关,例如tableguid、用户名、用户ID、角色等。但是,如果您希望跟踪用户何时登录/注销,或者使用自己的身份验证而不是表单身份验证,则此方法更适合。

如果您希望存储每个用户的值,我认为这些是我没有完全遵循的最佳选择,你能给我举个例子吗?我在回答中补充了更多的细节…谢谢你的例子和解释!