2009-01-28 67 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层架构轻松整合 - 我们一直都在这样做。