FormsAuthentication.RedirectFromLoginPage和FormAuthenticationTicket网络表单

时间:2018-12-24 16:59:55

标签: c# webforms

我仍然对Webforms还是陌生的,我有点困惑。我正在使用 受保护的无效btnLogin_Click(对象发送者,EventArgs e) {         字符串用户名= txtUsername.Text;         字符串密码= txtPassword.Text;         bool RememberUsername = false;         SqlDbAccess db =新的SqlDbAccess();         int result = db.ValidateLogin(用户名,密码);         切换(结果)         {             情况1:                 lblValidationError.Text =“实用程序/密码不正确”;                 打破;             情况-2:                 lblValidationError.Text =“继续激活”;                 打破;             默认:                 FormsAuthentication.RedirectFromLoginPage(txtUsername.Text,false);                 打破;         } } 而且因为我需要担任角色所以我有这个        字符串角色= db.GetRoles(result);         var ticket =新的FormsAuthenticationTicket         (             1,             用户名,             DateTime.Now,             DateTime.Now.AddMinutes(20),             记住用户名,             角色,             FormsAuthentication.FormsCookiePath         );         字符串hashCookies = FormsAuthentication.Encrypt(ticket);         HttpCookie cookie =新的HttpCookie(FormsAuthentication.FormsCookieName,hashCookies);         Response.Cookies.Add(cookie);         字符串returnUrl = Request.QueryString [“ ReturnUrl”];         如果(returnUrl == null)             returnUrl =“〜/ Default.aspx”;         Response.Redirect(returnUrl); 问题是...我必须同时使用两种FormsAuthentication方法还是可以仅使用票证?

1 个答案:

答案 0 :(得分:0)

FormsAuthentication.RedirectFromLoginPage的{​​{3}}状态:

  

将经过身份验证的用户重定向回原始请求的URL或默认URL。

注意单词“ authenticated” ...在第一个代码段中,您正在检查凭据并进行重定向。您正在 not 设置表单身份验证Cookie,就像在第二个片段中一样。我实际上认为组合的代码应如下所示:

protected void btnLogin_Click(object sender, EventArgs e)
{
    string username = txtUsername.Text;
    string password = txtPassword.Text;
    bool rememberUsername = false;

    SqlDbAccess db = new SqlDbAccess();
    int result = db.ValidateLogin(username, password);

    switch (result)
    {
        case -1:
            lblValidationError.Text = "Utilizador / Password incorrecto";
            break;
        case -2:
            lblValidationError.Text = "Conta desactivada";
            break;
        default:
            // not certain what should be passed in here???
            string roles = db.GetRoles(username);

            var ticket = new FormsAuthenticationTicket
            (
                1, 
                username, 
                DateTime.Now, 
                DateTime.Now.AddMinutes(20), 
                rememberUsername, 
                roles, 
                FormsAuthentication.FormsCookiePath
            );

            string hashCookies = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

            Response.Cookies.Add(cookie);
            FormsAuthentication.RedirectFromLoginPage(username, rememberUsername);
            break;
    }
}