使用WebForms登录后,在何处存储用户数据

eze*_*517 6 c# cookies session login

我正在使用C#中的VS2010开发WebForms Web应用程序.我使用自定义登录方法来验证用户,我不想使用Membership框架.用户登录后,我想将用户数据存储为userId,用户名,姓氏,电子邮件等,因此我可以在用户会话期间在所有页面中访问它们.

我怎样才能做到这一点?我不想将用户数据存储在UserData属性中FormsAuthenticationTicket.

我找到了这种方法:我应该在会话中存储用户数据还是使用自定义配置文件提供程序?,但我不明白如何实现它.

我有一些问题:
1)在我的登录页面中,在我使用db检查凭据后验证用户:FormsAuthentication.SetAuthCookie(txtUserName.Value,true); 现在在我的默认页面中我有:
FormsAuthenticationTicket ticket =((FormsIdentity)(User.Identity)).票证; 我使用ticket.Name来显示用户名.这是对的吗?你为什么要使用Thread.CurrentPrincipal.Identity.Name谈论线程?
2)我在global.asax文件中有这个代码来读取用户角色并将它们存储到HttpContext中:

void Application_AuthenticateRequest(object sender,EventArgs e){

    if (Request.IsAuthenticated) {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnStr"].ConnectionString);
        conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT Gruppi.Name FROM Ruoli INNER JOIN Gruppi ON Ruoli.GroupID = Gruppi.GroupID INNER JOIN Utenti ON Ruoli.UserID = Utenti.UserID AND Utenti.Username=@UserName", conn);      
        cmd.Parameters.AddWithValue("@UserName", User.Identity.Name);
        SqlDataReader reader = cmd.ExecuteReader();
        ArrayList rolelist = new ArrayList();         
        while (reader.Read()){
            rolelist.Add(reader["Name"]);
        }
          //  roleList.Add(reader("Name"))           
        string[] roleListArray = (string[])rolelist.ToArray(typeof(string));
        HttpContext.Current.User = new GenericPrincipal(User.Identity, roleListArray);

        reader.Close();
        conn.Close();
    }

}
Run Code Online (Sandbox Code Playgroud)

从我的global.asax文件而不是login.aspx页面写入时,我可以将用户数据存储到会话中吗?

Non*_*hal 5

为了便于调试,我建议使用此处描述的Session Facade设计模式,它允许您以HttpContext.Current.Session更有条理的方式使用对象存储当前用户的数据.

例如,会有一个文件(例如SessionFacade.cs)负责处理传递给/来自的值Session; 在您的情况下,它可能看起来像:

public static class SessionFacade
{
    public static int UserId
    {
        get {
            if (HttpContext.Current.Session["UserId"] == null)
                HttpContext.Current.Session["UserId"] = 0;
            return (int)HttpContext.Current.Session["UserId"];
        }
        set {
            HttpContext.Current.Session["UserId"] = value;
        }
    }
    // ... and so on for your other variables
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的代码中的其他地方,一旦您检查凭据是否正常,您就可以...

if (credentialsAreOk) {
    SessionFacade.UserId = /* insert ID here */
    // ...
}
Run Code Online (Sandbox Code Playgroud)

...而不是手动将值分配给Session对象.这可以确保您的变量Session类型正确,并且在调试时更容易跟踪.然后,要从程序中的任何位置获取UserId,它就是SessionFacade.UserId.

(是的,该片段来自Eduard的答案;您仍然应该查看答案,因为它提供了关于WebForms如何工作的信息;请记住,Session在您的代码中手动调用对象可能非常混乱,并且Session Facade进行该过程清洁器)