2009-01-28 91 views
1

簡單的方法我能夠驗證登錄頁面。我如何在3層體系結構中進行身份驗證?請有人向我發送DAL,BAL和GUI圖層中的代碼?這是我簡單的代碼:使用asp.net需要登錄身份驗證的幫助

Web.config文件:

<authentication mode="form"> 
    <form loginurl="Login.aspx"> 
     <credential password Format="clear"> 
      <user name="abcd" password="1234"> 
     </credential> 
     </authentication> 
    </form> 
    <authorization> 
    <deny users="?"> 
    </authorization> 

login.aspx.cs:

sqlconnection con=new sqlconnection("server=localhost;database=dbname;uid=;pwd=;Trusted_Connection=true"); 
sqldataAdapter da=new sqldataAdapter("select * from Login where UserName='"+TextBox1.Text+"' and Password='"+TextBox2.Text+"'",con); 
Dataset ds=new Dataset(); 
da.Fill(ds); 

if(ds.Tables[0].rows.Count>0) 
{ 
    if(FormAuthentication.Authenticate("abcd","1234") 
    { 
     FormAuthentication.RedirectFromLoginPage(TextBox1.Text,false); 
     Response.write("Logged in"); 
    } 
    else 
    { 
     Response.write("Unautherised User"); 
    } 

    Response.Redirect("welcome.aspx"); 
} 
else 
{ 
    Response.write("Sorry Invalid UserName or Password"); 
} 

回答

1

一般來說,你至少應該有以下類:

  • 在DAL中,您應該擁有一個數據庫連接類的類
  • 在BAl y你應該有一個表示每個用戶實例的類。這個類應該有一個名爲login()的方法,在該方法中進行所有的身份驗證和授權。
  • 表示用戶界面的Web表單。

此外,爲了防止SQL注入從不連接查詢字符串。改用參數。

下面是一些例子類:

namespace DAL 
{ 
    public class ConnectionManager 
    { 
     public static SqlConnection GetConnection() { 
      SqlConnection cn = new SqlConnection("server=localhost;database=dbname;uid=;pwd=;Trusted_Connection=true"); 
      cn.Open(); 
      return cn; 
     } 
    } 
} 

namespace BAL 
{ 
    public class User 
    { 
     public string UserName { get; set; } 
     public string Password { private get; set; } 

     public bool Login() { 
      return Login(this.UserName, this.Password); 
     } 

     public bool Login(string user, string password) { 
      bool success=false; 
      using (SqlConnection cn = ConnectionManager.GetConnection()) 
      { 
       string sql = "select count(*) from Login where [email protected] and [email protected]"; 
       using (SqlCommand command = new SqlCommand(sql, cn)) 
       { 
        command.Parameters["@user"].Value = user; 
        command.Parameters["@password"].Value = password; 
        success = (int)command.ExecuteScalar() > 0; 
       } 
       cn.Close(); 
      } 
      return success; 
     } 
    } 
} 
+0

如果我是你,我會把Sqlcommand和sql語句放在DAL中。 BLL應該簡單地調用DAL中的函數並傳遞用戶名和密碼作爲參數。 – Cerebrus 2009-01-28 07:29:57

0

略微虧本,爲什麼你會想推倒重來? ASP.NET Membership提供程序完成這一切,如果您需要大量修改其行爲,開放源碼,易於閱讀,理解和更改。它可以與您自己的n層架構輕鬆整合 - 我們一直都在這樣做。