C# ASP.NET登录控件cookies,它是如何工作的?

C# ASP.NET登录控件cookies,它是如何工作的?,c#,asp.net,cookies,C#,Asp.net,Cookies,我在我正在创建的网站上设置了一个登录控件,它可以正常工作。我可以查询我的数据库,如果详细信息与数据库匹配或失败,它将登录用户 这是我的密码: private bool UserLoginConnection(string user, string password) { SqlConnection sqlConnection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCom

我在我正在创建的网站上设置了一个登录控件,它可以正常工作。我可以查询我的数据库,如果详细信息与数据库匹配或失败,它将登录用户

这是我的密码:

private bool UserLoginConnection(string user, string password)
    {
        SqlConnection sqlConnection = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("Select userEmail from Users where userEmail = @user and userPassword = @password", sqlConnection);
        cmd.Parameters.AddWithValue("@user", user);
        cmd.Parameters.AddWithValue("@password", password);
        sqlConnection.Open();

        string result = Convert.ToString(cmd.ExecuteScalar());
        sqlConnection.Close();
        if (String.IsNullOrEmpty(result))
        {
            return false;
        }
        return true;

    }

    protected void UserLogin_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string user = UserLogin.UserName;
        string password = UserLogin.Password;
        bool result = UserLoginConnection(user, password);

        if (result)
        {
            e.Authenticated = true;
            Session["username"] = user;
        }
        else
        {
            e.Authenticated = false;
        }
    }
我的问题是关于饼干。我的理解是,如果我选中“记住我”框(由登录控件提供),表单身份验证模块将创建一个持久cookie

我想知道我对它工作原理的理解是否正确?我对这个解决方案很满意,只要它按照我认为的方式工作


注意:我知道我的代码可能不是最好的,但我是一个初学者,我每天都在学习

是的,你的假设是正确的

激发Authenticate事件后,它查看Authenticate的返回值

如果为true,则创建表单验证Cookie-

FormsAuthentication.SetAuthCookie(UserNameInternal, RememberMeSet); 
登录控件的AttemptLogin方法 其他想法 您不需要
会话[“username”]=user。如果使用表单身份验证,则可以使用User.Identity.Name线程的当前主体获取用户名

比如说,

string username = User.Identity.Name;

是的,你的假设是正确的

激发Authenticate事件后,它查看Authenticate的返回值

如果为true,则创建表单验证Cookie-

FormsAuthentication.SetAuthCookie(UserNameInternal, RememberMeSet); 
登录控件的AttemptLogin方法 其他想法 您不需要
会话[“username”]=user。如果使用表单身份验证,则可以使用User.Identity.Name线程的当前主体获取用户名

比如说,

string username = User.Identity.Name;

太好了,非常感谢你的回复。我不知道User.Identity.Name,因此我使用会话变量来隐藏面板(在我没有发布的代码的一部分中),这非常好,非常感谢您的回复。我不知道User.Identity.Name,因此我使用会话变量来隐藏面板(在我没有发布的代码的一部分中)