2010-07-05 65 views
2

下面的代碼和配置工作正常,但強制輸入用戶名/密碼大小寫敏感,我想讓它不區分大小寫。從FormsAuthentication.Authenticate刪除用戶名/密碼區分大小寫

代碼:

protected void LoginButton_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       string uid = UserText.Text.Trim(); 
       string pwd= PwdText.Text.Trim(); 

       if (string.IsNullOrEmpty(uid) || 
        string.IsNullOrEmpty(pwd)) 
       { 
        throw new ApplicationException("UserName or Password should not be blank."); 
       } 

       bool isAuthrnticated = FormsAuthentication.Authenticate(uid, pwd); 

       if (isAuthrnticated) 
       { 
        FormsAuthentication.SetAuthCookie("Admin", false); 

        //... 
       } 
       else 
       { 
        ((Site)this.Master).ShowError("Invalid UserName/Password.", ErrorSeverity.Warning); 
       } 
      } 
      catch (Exception ex) 
      { 
       ErrorLogger.LogError(ex); 
       ((Site)this.Master).ShowError(ex.Message, ErrorSeverity.Warning); 
      } 
     } 

的Web.Config

<authentication mode="Forms"> 
    <forms defaultUrl="~/Default.aspx" loginUrl="~/Default.aspx" slidingExpiration="true" timeout="1000"> 
    <credentials passwordFormat="Clear"> 
     <user name="Admin" password="ZAdmin"/> 
    </credentials> 
    </forms> 
</authentication> 

回答

4

默認情況下,用戶名不區分大小寫,並且密碼是。最簡單的方法是註冊時,將un和pw都更改爲ToUpper()或ToLower(),然後在進行身份驗證時,對輸入的任何內容執行相同操作。

string uid = UserText.Text.Trim().ToUpper(); 
string pwd= PwdText.Text.Trim().ToUpper(); 
1

當你存儲的用戶名和密碼,而不是存儲它們原來的樣子,先調用ToUpper的()在他們身上。然後對傳遞給FormsAuthentication.Authenticate()的字符串做同樣的事情。這樣,在比較之前,兩者都將被轉換爲全大寫版本,從而渲染案例無關緊要。

+0

就是這樣做的手工方式,有沒有這方面的任何配置,這樣就沒有必要改變代碼? – Lalit 2010-07-05 12:50:45

+0

+1與我同時回答同樣的問題,所以加上一個。 – 2010-07-05 13:06:39