加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用WebForms登录后存储用户数据的位置

发布时间:2020-12-15 04:23:50 所属栏目:百科 来源:网络整理
导读:我正在使用C#中的VS2010开发WebForms Web应用程序.我使用自定义登录方法来验证用户,我不想使用Membership框架.用户登录后,我想将用户数据存储为userId,用户名,姓氏,电子邮件等,因此我可以在用户会话期间在所有页面中访问它们. 我怎样才能做到这一点?我不想
我正在使用C#中的VS2010开发WebForms Web应用程序.我使用自定义登录方法来验证用户,我不想使用Membership框架.用户登录后,我想将用户数据存储为userId,用户名,姓氏,电子邮件等,因此我可以在用户会话期间在所有页面中访问它们.

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

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

我有一些问题:
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();
    }

}

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

解决方法

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

例如,将有一个文件(例如,SessionFacade.cs)负责处理传递给Session或从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使得工艺清洁)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读