簡體   English   中英

如何在登錄時驗證現有帳戶的點擊

[英]How to validate for existing account on login click

我目前有一個登錄表單,單擊“登錄”按鈕將調用以下方法:

protected void btnLogin_Click(object sender, EventArgs e)
    {
        AccountBLL accBLL = new AccountBLL();

        string username = tbUsername.Text;
        string password = accBLL.getAccount(username).Password;

        if (tbPassword.Text == password)
        {
            // Authenticate user
            string role = accBLL.getAccount(username).Role;

            // Create Form Authentication Ticket
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), false, role);

            // Encrypt the ticket
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            // Create cookie
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            // Add cookie to outgoing cookie collection
            Response.Cookies.Add(authCookie);

            // Redirect to the URL
            if (role == "admin")
                Response.Redirect("AdminHome.aspx");
            else if (role == "user")
                Response.Redirect("UserHome.aspx");
            else
                lblMsg.Text = "Invalid login!";
        }
        else
        {
            lblMsg.Text = "Invalid password.";
        }

        //string accountID = (Session["AccountID"]).ToString();
    }

但是,如果該帳戶不存在/尚未創建,我將在string password = accBLL.getAccount(username).Password;上收到空指針錯誤string password = accBLL.getAccount(username).Password; 因為傳遞給getAccount()方法的用戶名不存在。 所以我的問題是,我應該如何編輯代碼以實現某種形式的驗證,如果不存在傳遞用於檢索密碼的userid的事件,則會向用戶顯示錯誤消息?

好吧,您自己說過,當提供的用戶名不存在時,方法getAccount返回null。 如果是我,我將檢查accBLL.getAccount(username)是否返回null。 如果是這樣,我將不執行其余代碼,而是向用戶顯示一條標簽,提示用戶輸入的用戶名不存在。

首先檢查用戶名是否存在,如果存在,然后檢查密碼是否正確。

我希望這有幫助。

更改這些行

 
 
 
 
  
  
  string password = accBLL.getAccount(username).Password; if (tbPassword.Text == password)
 
 
  

為此。

var account == accBLL.getAccount(username);
if (account != null && tbPassword.Text == account.Password)

在您的GetAccount方法中,比較null,例如fill dt,然后比較dt

if (dt.rows.count==0)
{
return null;
}

如果尚未創建帳戶,則將返回null值。 然后您的登錄按鈕單擊事件將如下所示。

 protected void btnLogin_Click(object sender, EventArgs e)
        {
            AccountBLL accBLL = new AccountBLL();

            string username = tbUsername.Text;
            string password = accBLL.getAccount(username).Password;
            if(password != null)
    {
            if (tbPassword.Text == password)
            {
                // Authenticate user
                string role = accBLL.getAccount(username).Role;

                // Create Form Authentication Ticket
              ..... your remaining code including else

    }
    else 
    {
    lblMsg.Text = "Account Doesnt Exist";
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM