gpt4 book ai didi

c# - 使用 WebForms 登录后在何处存储用户数据

转载 作者:太空狗 更新时间:2023-10-29 21:22:48 25 4
gpt4 key购买 nike

我正在使用 C# 中的 VS2010 开发 WebForms Web 应用程序。我使用我的自定义登录方法来验证用户,我不想使用成员资格框架。用户登录后,我想将用户数据存储为用户 ID、用户名、姓氏、电子邮件等,以便我可以在所有页面的用户 session 期间访问它们。

我该怎么做?我不想将用户数据存储在 FormsAuthenticationTicketUserData 属性中。

我发现了这种方法:Should I store user data in session or use a custom profile provider? , 但我不明白如何实现它。

我有一些问题:
1) 在我的登录页面中,在我使用的数据库上检查凭据后对用户进行身份验证:FormsAuthentication.SetAuthCookie(txtUserName.Value, true);现在在我的默认页面中我有:
FormsAuthenticationTicket ticket = ((FormsIdentity)(User.Identity)).Ticket;我使用 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();
}

}

我可以像您从我的 global.asax 文件而不是 login.aspx 页面写入的那样将用户数据存储到 session 中吗?

最佳答案

为了更容易调试,我建议使用 Session Facade 设计模式,described here ,这将允许您以更有条理的方式使用 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
}

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

if (credentialsAreOk) {
SessionFacade.UserId = /* insert ID here */
// ...
}

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

(是的,该片段来自 Eduard 的回答;您仍然应该查看该回答,因为它提供了关于 WebForms 如何工作的信息;请记住,在您的代码中手动调用 Session 对象可以非常困惑,Session Facade 使该过程更干净)

关于c# - 使用 WebForms 登录后在何处存储用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com